如何在delete语句中使用Sum和Inner Join

时间:2017-05-08 20:58:43

标签: mysql sql phpmyadmin

我有一个名为TableName的表,我希望delete来自其产品数量SUM小于2的所有行。 我需要inner join表格oc_order_productSUM具有相同product_id的值,然后在SUM所有行的where子句中使用此deleteSUM小于2。 我现在正在使用以下查询:

  Delete TablenName from TablenName
        INNER JOIN oc_order_product 
                     ON oc_order_product.product_id = TablenName.product_id
   where oc_order_product.quantity HAVING SUM(oc_order_product.quantity) < 2;

我收到以下错误:

    #1064 - You have an error in your SQL syntax; check the manual that
 corresponds to your MariaDB server version for the right syntax 
to use near 'HAVING SUM(oc_order_product.quantity) < 2' at line 4

1 个答案:

答案 0 :(得分:2)

嗯。嗯。 。 。如果您需要进行聚合,则需要在join

之前执行此操作
Delete t
    from TablenName t join
         (select op.product_id, sum(op.quantity) as sumquantity
          from oc_order_product op
          group by op.product_id
         ) op
         on op.product_id = t.product_id and op.sumquantity < 2;