删除一列中具有重复值但在另一列中具有不同值的行

时间:2013-12-26 10:39:25

标签: mysql subquery mysql-error-1064 duplicate-removal delete-row

我在MariaDB 5.5中有一个表,如下所示:

| PRODUCT_ID | STORE_ID |
-------------------------
|        111 |        0 |
|        111 |        1 |
|        112 |        0 |
|        112 |        1 |
|        113 |        0 |
|        114 |        1 |
|        115 |        1 |
|        116 |        0 |
|        117 |        0 |
|        117 |        1 |

我想要的是按列product_id删除所有重复的行,其中store_id的值为0,因此最终的表格如下所示:

| PRODUCT_ID | STORE_ID |
-------------------------
|        111 |        1 |
|        112 |        1 |
|        113 |        0 |
|        114 |        1 |
|        115 |        1 |
|        116 |        0 |
|        117 |        1 |

此sql查询按列product_id返回所有重复条目:

SELECT `product_id` FROM `table` GROUP BY `product_id` HAVING COUNT(*) > 1

所以我尝试了这个:

DELETE FROM `table` AS a WHERE a.`store_id` = '0' AND a.`product_id` IN (SELECT b.`product_id` FROM  `table` AS b GROUP BY b.`product_id` HAVING COUNT(*) > 1)

但它在sql语法中给出了一个错误:

#1064 - 您的SQL语法出错;查看与您的MariaDB服务器版本对应的手册,以便在'AS a WHERE a .store_id` ='0'和.product_id` IN附近使用正确的语法(在第1行选择b .product_id` FROM'

这个错误的原因是什么,我应该使用什么查询?

1 个答案:

答案 0 :(得分:3)

此查询将删除所有STORE_ID = 0且重复的行:

DELETE t1.*
FROM
  yourtable t1 INNER JOIN (SELECT PRODUCT_ID
                           FROM yourtable
                           GROUP BY PRODUCT_ID
                           HAVING COUNT(*)>1) t2
  ON t1.PRODUCT_ID = t2.PRODUCT_ID
     AND t1.STORE_ID=0;

请参阅小提琴here