MYSQL 如果具有指定值的相同 table 中存在重复键,则删除行

MYSQL DELETE row if duplicate key exists in same table with specified value

这可能被标记为重复,但我无法在搜索中找到该示例。

我有一个允许重复键的产品到类别 table,因此允许按 ID 将产品放在多个类别中。我遇到过数千种产品被错误地归入一个类别的情况。如果产品分配给 'Action Figures' 和 'Comics',则 'Comics' 分配是错误的。

我正在尝试编写一个 MYSQL 查询,如果检测到具有重复键和 'Action Figures' 的指定值的行,该查询将删除行。换句话说:如果一个产品被分配到两个类别,那么我想删除将它分配到错误类别的行。

我似乎想不出可以按我想要的方式在同一 table 中按 ID 搜索的删除语句。

这是我到目前为止得到的(编辑-感谢下面的回答):

DELETE FROM oc_product_to_category c1
WHERE c1.category_id = '25'
AND EXISTS(
SELECT * FROM oc_product_to_category c2 
WHERE c1.product_id = c2.product_id AND c2.category_id = '24')

不幸的是,这会产生语法错误。

You have an error in your SQL syntax; 
check the manual that corresponds to your MySQL server version for the right syntax to use near 
'c1
WHERE c1.category_id = '25'
AND EXISTS (
SELECT * FROM oc_product_to_catego' at line 1

当我尝试语法时

DELETE c1 FROM oc_product_to_category c1 ...

我得到一个错误:

You can't specify target table 'c1' for update in FROM clause

这应该可以帮助您入门。如果 ID 分配给 category_id 25 和 33,它将删除类别为 25 的记录。

DELETE c1 FROM oc_product_to_category as c1
WHERE c1.category_id = '25'
AND EXISTS (
    SELECT id FROM (SELECT * FROM oc_product_to_category) as c2 
    WHERE c1.id = c2.id AND c2.category_id = '33'
)

请注意,这不会删除带有 category_id 33(如果存在)的重复记录。