MySQL根据查询结果删除

标签 mysql database sql-delete

我有以下 mysql 查询,它从我的数据库中的 pokemon 表中找到最近修改和唯一的 spawnpoint_id:

SELECT 
    t1.spawnpoint_id, t1.last_modified
FROM
    pokemon t1
        INNER JOIN
    (SELECT 
        MAX(last_modified) last_modified, spawnpoint_id
    FROM
        pokemon
    GROUP BY spawnpoint_id) t2 ON 
    t1.spawnpoint_id = t2.spawnpoint_id
    AND t1.last_modified = t2.last_modified;

我得到了我想要的结果....但是现在,我想删除所有匹配这些结果的记录。

我试图将查询包含在 DELETE .. NOT IN 中像这样:

DELETE FROM pokemon WHERE (spawnpoint_id, last_modified) NOT IN (
SELECT 
    t1.spawnpoint_id, t1.last_modified
FROM
    pokemon t1
        INNER JOIN
    (SELECT 
        MAX(last_modified) last_modified, spawnpoint_id
    FROM
        pokemon
    GROUP BY spawnpoint_id) t2 ON 
    t1.spawnpoint_id = t2.spawnpoint_id
    AND t1.last_modified = t2.last_modified) x;

但我收到 MySQL 语法错误。我已经搜索了几个小时,最后希望这里有人可以帮助我发现我做错了什么。非常感谢。

编辑:SHOW CREATE TABLE pokemon;

CREATE TABLE <code>pokemon</code> ( <code>encounter_id</code> varchar(50) NOT NULL, <code>spawnpoint_id</code> varchar(255) NOT NULL, <code>pokemon_id</code> int(11) NOT NULL, <code>latitude</code> double NOT NULL, <code>longitude</code> double NOT NULL, <code>disappear_time</code> datetime NOT NULL, <code>individual_attack</code> int(11) DEFAULT NULL, <code>individual_defense</code> int(11) DEFAULT NULL, <code>individual_stamina</code> int(11) DEFAULT NULL, <code>move_1</code> int(11) DEFAULT NULL, <code>move_2</code> int(11) DEFAULT NULL, <code>last_modified</code> datetime DEFAULT NULL, <code>time_detail</code> int(11) NOT NULL, PRIMARY KEY (<code>encounter_id</code>), KEY <code>pokemon_spawnpoint_id</code> (<code>spawnpoint_id</code>), KEY <code>pokemon_pokemon_id</code> (<code>pokemon_id</code>), KEY <code>pokemon_disappear_time</code> (<code>disappear_time</code>), KEY <code>pokemon_last_modified</code> (<code>last_modified</code>), KEY <code>pokemon_time_detail</code> (<code>time_detail</code>), KEY <code>pokemon_latitude_longitude</code> (<code>latitude</code>,<code>longitude</code>) ) ENGINE=InnoDB DEFAULT CHARSET=utf8

最佳答案

我认为问题在于您在子查询的起始部分(这是不允许的)使用表 pokemon,您希望从中删除行。

可以通过首先执行标记要删除的行的更新语句,然后执行单独的删除语句来解决此问题。请注意,“不得在源部分中使用”限制也适用于更新语句。然而,这可以通过使用连接而不是子选择来解决,如下所示:

create table a (
  x int,
  y int
);

insert into a (x,y) values (1,2),(3,4);

update a a1, (select max(a2.x) as x from a a2) a3 set a1.y = 0 where a1.x = a3.x;

delete from a where y=0

关于MySQL根据查询结果删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41419536/

相关文章:

mysql - 是否可以在 SQL 中的 SELECT 中合并?

sql - 在 SQL Azure 中设计可扩展数据库时需要帮助

php - 导入 CSV 到 MySql,如果重复,更新选择的值

mysql - 有没有某种方法可以测量结果与全文查询的匹配程度?

mysql - 如何干净地重新安装 zoneminder?

sql - Ms Access 连接不同数据库中的表

mysql - 我希望从连接中包含的所有 SQL 表中删除

php - 在一个查询中从多个表中删除行

php - 通过 id 和 parent_id 删除

mysql - 如何解决此错误 "MySQL Error: 1109 (Unknown table ' table_name' in MULTI DELETE)”?