我有两张桌子
订单表
or_id count status
1 2 0
2 3 0
3 2 0
Order_Details表
ordetail or_id status
1 1 1
2 1 1
3 2 0
4 2 1
5 2 1
6 3 1
7 3 1
如果在Order_Details表中对应的order_id的所有状态都是1,我希望更新订单表状态为1.我尝试使用此查询,但由于子查询返回的行超过1行,因此无法正常工作
UPDATE order o JOIN order_detail od ON o.or_id = od.or_id SET o.Status = 1 WHERE
o.or_id= (SELECT or_id FROM order_detail GROUP BY or_id
HAVING SUM(status = 1) = COUNT(*) )
提前致谢
答案 0 :(得分:3)
首先根据状态更新查询:
UPDATE `order` o
JOIN Order_Detail od ON o.or_id = od.order_id
SET o.Status = 1
WHERE od.Status = 1
要检索的第二个查询:
SELECT DISTINCT order_id
FROM Order_Detail
WHERE status = 0
注意:如果订单有2个order_details,1)status = 0且2)status = 1.上面的查询将包含该订单 - 因为有一行status = 0.如果你只想检索订单ID都是status = 0.然后使用此查询:
SELECT order_id
FROM Order_Detail
GROUP BY order_id
HAVING SUM(status = 0) = COUNT(*)
更新:根据评论,由于您只想在所有订单详细信息均为1时设置status = 1,请使用此更新查询:
UPDATE `order` o
JOIN (
SELECT order_id
FROM Order_Detail
GROUP BY order_id
HAVING SUM(status = 1) = COUNT(*)
) og ON o.or_id = og.order_id
SET o.Status = 1