简体   繁体   中英

Update a table by selecting data from another table MySQL query

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM