【发布时间】:2017-01-01 22:19:17
【问题描述】:
我有以下 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 语法错误。我一直在寻找几个小时,最后希望这里的人可以帮助我发现我做错了什么。非常感谢。
编辑:显示创建表口袋妖怪;
CREATE TABLE pokemon (
encounter_id varchar(50) NOT NULL,
spawnpoint_id varchar(255) NOT NULL,
pokemon_id int(11) NOT NULL,
latitude double NOT NULL,
longitude double NOT NULL,
disappear_time datetime NOT NULL,
individual_attack int(11) DEFAULT NULL,
individual_defense int(11) DEFAULT NULL,
individual_stamina int(11) DEFAULT NULL,
move_1 int(11) DEFAULT NULL,
move_2 int(11) DEFAULT NULL,
last_modified datetime DEFAULT NULL,
time_detail int(11) NOT NULL,
PRIMARY KEY (encounter_id),
KEY pokemon_spawnpoint_id (spawnpoint_id),
KEY pokemon_pokemon_id (pokemon_id),
KEY pokemon_disappear_time (disappear_time),
KEY pokemon_last_modified (last_modified),
KEY pokemon_time_detail (time_detail),
KEY pokemon_latitude_longitude (latitude,longitude)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
【问题讨论】:
-
请用实际错误更新帖子。
-
查询很别扭。如果要从 table1 中删除 table2 中不存在的行,只需执行以下操作: DELETE FROM tablle1 WHERE (table1.spawnpoint_id, table1.last_modified) NOT IN ( SELECT table2.spawnpoint_id, table2.last_modified from table2)
-
错误似乎是:“错误代码:1093。您不能在 FROM 子句中指定目标表 'pokemon' 进行更新” ...这就是为什么我认为添加 'x' 会解决那个。关于“尴尬”的查询,也许是这样。我想删除口袋妖怪表中具有不同'spawnpoint_id'除了最近的'last_modified'记录的所有记录......我可以按照我的描述选择那些记录,只是不知道最好的方法现在删除那些 不是 他们...
标签: mysql database sql-delete