我有以下 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/