2017-01-01 131 views
1

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

回答

1

我認爲問題在於你使用表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