DELETE FROM 抛出 SQL Error [1064] [42000]: (conn=5159) on a query, SELECT works

DELETE FROM throws a SQL Error [1064] [42000]: (conn=5159) on a query, on which a SELECT works

尝试在 MySQL 查询中删除特定数量的行,我可以 SELECT 使用以下命令删除任何我想删除的内容,得到我需要的结果:

select * from ns_cos ns where ns.created_at <>
    (select max(nsa.created_at) from ns_cos nsa
        where nsa.month_year = ns.month_year)

但是,当我尝试删除所选数据时:

delete from ns_cos ns where ns.created_at not exists
    (select max(nsa.created_at) from ns_cos nsa
        where nsa.month_year = ns.month_year)

我得到:

SQL Error [1064] [42000]: (conn=5159) 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 'ns where ns.created_at not exists (select max(nsa.created_at) from ns_cos nsa wh' at line 1

我做错了什么?

EXISTS 不可能使用 IN 子句,但您需要将 table 括在单独的 select 中,以便 mysql 认为它是另一个 table

delete from ns_cos ns 
where ns.created_at not IN (select max(nsa.created_at) from (SELECT * FROM ns_cos) nsa where nsa.month_year = ns.month_year)

您的直接问题是并非所有 MySQL 版本都支持直接在 delete from 中为 table 添加别名。此外,尽管如此,您不能 re-open table 您在 from 子句中删除 from

考虑使用 delete ... join 语法。

delete ns
from ns_cos ns
inner join (
    select month_year, max(nsa.created_at) created_at
    from ns_cos nsa 
    group by month_year
) ns1 on ns1.month_year = ns.month_year and ns1.created_at <> ns.created_at