如何在delete语句中使用Sum和Inner Join并向其添加第三个表

时间:2017-05-09 04:43:44

标签: mysql sql phpmyadmin

此问题是对此处回答的以下问题的补充 How to use Sum and Inner Join in a delete statement

我需要将以下where语句WHERE oc_order_status.order_status_id IN ('3','5','17','19','20','23','25','26','29')添加到以下查询中:

Delete t
    from TablenName t join
         (select op.product_id, sum(op.quantity) as quantity
          from oc_order_product op
          group by op.product_id
         ) op
         on op.product_id = t.product_id and op.quantity < 2;

所有表共享具有相同值的product_id列,并且所有表都在同一个数据库中。

1 个答案:

答案 0 :(得分:2)

您可以使用FK inner join执行product_id产品和状态表,并过滤掉where子句中的order_status_id

Delete t
    from TablenName t join
         (select op.product_id, sum(op.quantity) as quantity
          from oc_order_product op
          inner join oc_order_status os on os.product_id =op.product_id
          where os.order_status_id IN (3,5,17,19,20,23,25,26,29)
          group by op.product_id
         ) op
         on op.product_id = t.product_id and op.quantity < 2;