mysql - DELETE FROM 抛出 SQL 错误 [1064] [42000] : (conn=5159) on a query,,而 SELECT 在该错误上

标签 mysql sql mariadb subquery sql-delete

尝试在 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

我做错了什么?

最佳答案

您面临的直接问题是,并非所有 MySQL 版本都支持直接在 delete from 中为表添加别名。此外,您无法重新打开在 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

关于mysql - DELETE FROM 抛出 SQL 错误 [1064] [42000] : (conn=5159) on a query,,而 SELECT 在该错误上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63745298/

相关文章:

mysql - MariaDB 复制 - 由于中继日志中的 gtid 语句导致从属滞后

php - mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows 等...期望参数 1 是资源

php - 如果使用 PHP 用户的时区发生更改,如何处理存储在数据库中的用户数据

php - DBO 选择等于和喜欢的地方

sql - 在 Oracle 中使用 MODEL 子句并返回以前的值

mysql - SQL语句where子句中的条件

mysql - 在具有 mysql 数据库的 Rails 3 应用程序中保存日期时间时遇到问题

MySQL : date format not working with OR in where condition

php - 使用 in () 的 Mysql 查询不起作用

mysql - PDO:从包含反斜杠的数据库中选择字段