MySQL的删除基于查询结果

问题描述:

我有以下MySQL查询其找到最近修改的和独特的spawnpoint_id从口袋妖怪表在我的数据库:MySQL的删除基于查询结果

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 pokemonencounter_id VARCHAR(50)NOT NULL, spawnpoint_id VARCHAR(255)NOT NULL, pokemon_id INT(11)NOT NULL, latitude双NOT NULL, longitude双NOT NULL, disappear_time日期时间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日期时间DEFAULT NULL, time_detail INT(11)NOT NULL, PRIMARY KEY(encounter_id) KEY pokemon_spawnpoint_idspawnpoint_id) KEY pokemon_pokemon_idpokemon_id) KEY pokemon_disappear_timedisappear_time ), KEY pokemon_last_modifiedlast_modified) KEY pokemon_time_detailtime_detail) KEY pokemon_latitude_longitudelatitudelongitude) )ENGINE = InnoDB的默认字符集= UTF8

+0

见http://meta.*.com/questions/333952/why-should-i-provide-an-mcve-for:但是这可以通过使用一个连接,而不是一个子查询如下解决什么似乎对我来说是一个非常简单的SQL查询 – Strawberry

+0

请更新与帖子的实际错误。 – Aaron

+0

查询很尴尬。如果要删除table1中不存在于table2中的行,只需执行以下操作:DELETE FROM tablle1 WHERE(table1.spawnpoint_id,table1.last_modified)NOT IN( SELECT table2.spawnpoint_id,table2.last_modified from table2) – user3606329

我认为问题在于你使用表pokemon,你想删除行,在子查询的部分(这是不允许的)。

可以通过首先执行一条标记要删除的行的update语句来解决此问题,然后执行单独的删除语句。请注意,“不得在部件中使用”限制也适用于更新语句。

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 
+0

斯蒂芬,谢谢。不幸的是,这个答案飞过了我的脑海。我喜欢标记要删除的行的想法(也许只是添加一个新列?),并使用类似的插入语句,然后执行删除...我会试验。 – Kelly