mysql - 如何同时从同一个表中选择从 SQL 表中删除行

标签 mysql sql sql-delete

我正在尝试删除表中除具有最大值 revision_id 的行之外的所有行value同时从同一个表中选择数据:

delete from
  node_revision__body
where
  entity_id=4 
  and revision_id not in (
    select
      max(revision_id)
    from
      node_revision__body
    where
      entity_id=4
    )

这会引发错误

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

是否可以以某种方式更改查询以实现目标?

最佳答案

这是一个documented MySql 的“功能”,您无法更新您选择的同一个表,但是存在一些解决方法,例如您可以尝试将查询嵌套更深一层:

delete from node_revision__body
where entity_id = 4 
  and revision_id not in (
    select revision_id from (
      select max(revision_id) revision_id
      from node_revision__body
      where entity_id = 4
    )b
);

查看working demo

关于mysql - 如何同时从同一个表中选择从 SQL 表中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74762297/

相关文章:

php - 如何统计具有相似条件的2个表的mysql结果?

php - 我已将信息插入我的数据库中,并且我也已验证它。但如果我点击插入它会重定向到另一个页面

sql - 如果我的数据库列有很多空值,为什么我不应该在它上面使用索引?

javascript - AJAX + jQuery 困惑?

SQL Server - 使用 SQL 删除日期范围之间的行。日期转换失败

c# - 从datagridview中删除数据库

php - 使用准备好的语句插入失败时出现 Errno(0)

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

MySQL 加入查询 GROUP BY

mysql - PHP MYSQL 删除一定数量(5)行