[英]Update parent table column only if all the values of child table rows are a specific value
I have 2 tables, orders and order_items.我有 2 个表,orders 和 order_items。 Each order can have multiple order_items.
每个订单可以有多个 order_items。
An order has an id
and orderStatus
:一个订单有一个
id
和orderStatus
:
An order_item as id
, orderId
and orderItemStatus
:一个 order_item 作为
id
, orderId
和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
.我想更新的
status
,从订单的的OPEN
来FULFILLED
,如果所有订单的ORDER_ITEMS有status
的ISSUED
。 If at least one order_item is not ISSUED
, the order status
should remain as OPEN
.如果至少有一个 order_item 不是
ISSUED
,则订单status
应保持为OPEN
。 How can I do this?我怎样才能做到这一点?
You can use a NOT EXISTS subquery as condition.您可以使用 NOT EXISTS 子查询作为条件。
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'.这只会更新状态为“OPEN”且没有状态为“ISSUED”的商品的订单。
You could check for orders_item with status ISSUED if this is the unique status如果这是唯一状态,您可以检查状态为 ISSUED 的 orders_item
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.