【问题标题】:MYSQL- Error #1054MYSQL - 错误 #1054
【发布时间】:2015-09-10 03:57:58
【问题描述】:

插入之前链接中提到的编码后,我注意到ORDER 表中的Total_Price 中的某些值仍然为零。这可能是因为DRINK_ORDER 表中的Total_Price 中有一些值可能为空。我尝试使用下面提到的编码,它给了我“#1054 - 'where 子句'中的未知列'FOOD_ORDER.Order_ID'”。谁能帮帮我吗?

顺便说一下ORDER.Total_Price = FOOD_ORDER.Total Price + DRINKS_ORDER.Total_PRICE (仅供参考)

Previous work

UPDATE `ORDER`
    SET Total_Price = SUM (food_order.Total_Price)  
    WHERE FOOD_ORDER.Order_ID =`ORDER`.Order_ID
    AND `ORDER`.Total_Price = 0;

【问题讨论】:

  • 需要使用连接模式来跟踪更新

标签: mysql


【解决方案1】:

架构:

create table `order` -- not a great name by the way
(   Order_Id int auto_increment primary key,
    Total_Price decimal (10,2) not null
);

create table food_order
(   id int auto_increment primary key,
    Order_Id int not null,
    Total_Price decimal(10,2) not null, -- line item total price
    key(Order_Id), -- make it fast
    -- FK below
    CONSTRAINT fk_fo_toOrder FOREIGN KEY (Order_Id) REFERENCES `order`(Order_Id) 
);

create table drink_order
(   id int auto_increment primary key,
    Order_Id int not null,
    Total_Price decimal(10,2) not null, -- line item total price
    key(Order_Id), -- make it fast
    -- FK below
    CONSTRAINT fk_do_toOrder FOREIGN KEY (Order_Id) REFERENCES `order`(Order_Id) 
);

insert `order`(total_price) values (0),(0),(0); -- 3 orders
insert food_order(Order_Id,Total_Price) values (1,1.11),(1,2.22),(1,4.44),(2,20),(2,11.11);
insert drink_order(Order_Id,Total_Price) values (2,22.22),(2,33.33),(3,1000),(3,2000);

查询(由 Order_Id 单独运行)

update `Order`
join
(
select o.Order_Id,food.foodSum,drinks.drinkSum
from `order` o
cross join
( select ifnull(sum(Total_Price),0) as foodSum
  from food_order
  where Order_Id=1
) food
cross join 
( select ifnull(sum(Total_Price),0) as drinkSum
  from drink_order
  where Order_Id=1
) drinks
where o.Order_id=1
) inr
on inr.Order_id=`Order`.Order_Id
set `Order`.Total_Price=(inr.foodSum+inr.drinkSum);

结果:

select * from `order`;
+----------+-------------+
| Order_Id | Total_Price |
+----------+-------------+
|        1 |        7.77 |
|        2 |       86.66 |
|        3 |     3000.00 |
+----------+-------------+

注意,Order_Id 可以与准备好的语句一起放入,或者存储过程可以接受一个参数,并以这种方式将其楔入。

cross join 指定没有连接子句。通常被认为是cartesian product,但在这种情况下,结果为 1*1*1 = 1 行。

所以它是join with update pattern,针对 1 行。

就数据而言,订单 1 没有饮料,订单 3 没有食物,订单 2 两者都有。我认为订单 3 很有趣。

【讨论】:

  • 我的意思是,当一个订单只包含 Food_Order 而没有 Drinks_Order 时(例如,餐厅里的一个人只点食物而不点饮料)ORDER table 中的总价格值为 0。你展示的例子并不能真正帮助我解决这个问题
  • 抱歉造成误会
  • np。是Total_Pricefood_order 还是drink_order nullnot null(表定义)
  • 我在两个表中都为Total_Price 设置了not null
猜你喜欢
  • 2016-02-07
  • 2018-01-06
  • 2011-10-10
  • 2016-04-01
  • 2012-03-09
  • 1970-01-01
  • 2016-01-04
  • 2010-11-17
  • 2017-04-07
相关资源
最近更新 更多