开发者

Update a table by selecting data from another table MySQL query

开发者 https://www.devze.com 2023-02-12 21:40 出处:网络
I have two tables Order Table or_idcount status 120 230 320 Order_Details Table ordetailor_idstatus 111 211 320

I have two tables

Order Table

or_id  count status
1        2    0
2        3    0
3        2    0

Order_Details Table

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

I want update order table status to 1 if all the status of the corresponding order_id is 1 in Order_Details Table.I tried to work with this query, but it is not working since Subquery returns more than 1 row

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(*) ) 

Thanks in advance


First query to update based on status:

UPDATE `order` o
  JOIN Order_Detail od ON o.or_id = od.order_id
SET o.Status = 1
WHERE od.Status = 1 

Second query to retrieve:

SELECT DISTINCT order_id
FROM Order_Detail
WHERE status = 0

Note: If a order has 2 order_details, 1) with status = 0 and 2) status = 1. the above query will include that order - since there is a row with status = 0. If you want to only retrieve the order id's that are all status = 0. then use this query:

SELECT order_id
FROM Order_Detail
GROUP BY order_id
HAVING SUM(status = 0) = COUNT(*)

Update: As per comments, since you want to set status = 1 only if all the order details are 1, use this update query:

 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号