I have 2 tables, orders and order_items. Each order can have multiple order_items.
An order has an id
and orderStatus
:
An order_item as id
, orderId
and orderItemStatus
:
I want to update the status
of order's from OPEN
to FULFILLED
if all an order's order_items have status
of ISSUED
. If at least one order_item is not ISSUED
, the order status
should remain as OPEN
. How can I do this?
You can use a NOT EXISTS subquery as condition.
update order o
set o.orderStatus = 'FULFILLED'
where o.orderStatus = 'OPEN'
and not exists (
select *
from order_item i
where i.orderId = o.id
and i.orderItemStatus <> 'ISSUED'
)
This will only update orders which have status 'OPEN' and have no items with status 'ISSUED'.
You could check for orders_item with status ISSUED if this is the unique status
update orders o
inner join (
select orderID, count( dictinct orderItemStatus)
from order_item
group by orderID
having count( dictinct orderItemStatus) = 1
) t on t.orderID = o.id
inner join order_item i on i.orderID = o.id
AND orderItemStatus = 'ISSUED'
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.