mysql 删除重复项时出现语法错误

mysql syntax error on removing duplicates

我正在尝试使用此查询删除具有重复 hid 列值的行:

DELETE FROM dmf_product_match_unmatches as pmu1
WHERE ID not in 
(
    SELECT MAX(ID) as maxRecId
        FROM dmf_product_match_unmatches as pmu2
        GROUP BY hid       
);

但这给了

QL Error [1064] [42000]: 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 'as pmu1
WHERE ID not in 
(
    SELECT MAX(ID) as maxRecId
        FROM dmf_prod' at line 1

查询看起来不错。我在这里错过了什么?

documentation on DELETE 在页面顶部的语法参考中没有明确说明,但是如果您为 table 定义别名,则必须使用如下语法:

DELETE pmu1 FROM dmf_product_match_unmatches as pmu1
...

原因是使用 as 关键字会使解析器认为您正在使用 multi-table delete 语法,即使您只引用了一个 table外部查询。我链接到的文档中的语法参考显示,如果您使用 table_references 语法,则需要 DELETE tbl_name FROM ... 语法,如果您使用 as关键字。

文档下方确实有注释:

If you declare an alias for a table, you must use the alias when referring to the table:

DELETE t1 FROM test AS t1, test2 WHERE ...

或者,您不需要在此查询中定义别名,因此您可以使用更简单的语法:

DELETE FROM dmf_product_match_unmatches
...

当错误消息由于某种未知原因与错误不匹配时就是这种情况。我不明白为什么会这样 - 在 CLI 中执行时,错误消息必须是

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

错误的根源 - 您不能使用 table 更改为 WHERE 中的子查询的数据源。

您必须改用多重 table DELETE 语法:

DELETE pmu1
FROM dmf_product_match_unmatches as pmu1
LEFT JOIN ( SELECT MAX(ID) as ID, hid
            FROM dmf_product_match_unmatches as pmu2
            GROUP BY hid) pmu3 USING (ID, hid)
WHERE pmu3.ID IS NULL;

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=202cddc698cda3f83e0172c7e4e28a7d