简体   繁体   English

仅当子表行的所有值都是特定值时才更新父表列

[英]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 :一个订单有一个idorderStatus

在此处输入图片说明

An order_item as id , orderId and orderItemStatus :一个 order_item 作为idorderIdorderItemStatus 在此处输入图片说明

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 ,从订单的的OPENFULFILLED ,如果所有订单的ORDER_ITEMS有statusISSUED 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.

相关问题 将列值更新为同一表中特定值的COUNT行 - Update a column value to the COUNT of rows for specific values in same table 如何更新表 A 中所有行的值应更新表 b 和 c 中的所有对应列值 - How to update value for all rows in table A should update all corresponding column values in table b and c 根据另一个表中没有子行更新表的列值 - UPDATE column values of a table based on no child rows in another table 仅按特定行显示所有数据组:从具有column =&#39;value&#39;的列的表组中选择* - show all data only group by specific rows : Select * from table group by column having column = 'value' MySQL-特定列上的更新触发器之后会影响表中的所有行 - MySQL - After Update Trigger on Specific Column affects all rows in the table Mysql 用同一表列的计数更新所有行值 - Mysql update all rows value with count of same table column 从父表中选择子表的所有行都满足某个值 - Select from parent table where all rows of child table meets a certain value 如何对按父表中的列分组的子表中的行进行求和 - How to sum rows from a child table grouped by a column in parent table 按子表中列的 SUM 对父表中的行进行排序 - Ordering rows in a parent table by SUM of column in a child table MySQL的:从父表中选择,只有当子表有行 - Mysql: Select from parent table, only if child table has rows
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM