2014-01-16 35 views
1

嗨我試圖解決哪些元素不存在於我的數據庫中。爲了做到這一點,我想比較表中的數據(從外部腳本輸出)與數據列表。如何做這樣的事情,如:MySQL從自定義集中選擇並與表數據進行比較

SELECT * FROM (1,1,2,3,5,8,13...) l WHERE l NOT IN (select id from table1); 

回答

3

這可能是最好的與left outer join完成。但是,你的問題是創造的常數表:

SELECT * 
FROM (select 1 as id union all select 2 union all select 3 union all select 5 union all 
     select 8 union all select 13 union all select 21 . . . 
    ) ids 
where ids.id NOT IN (select id from table1); 

這可能有奇怪的行爲,如果table1.id是有史以來NULL。下面的作品更普遍:

SELECT * 
FROM (select 1 as id union all select 2 union all select 3 union all select 5 union all 
     select 8 union all select 13 union all select 21 . . . 
    ) ids left outer join 
    table1 t1 
    on ids.id = t1.id 
where t1.id is null; 

編輯:

MySQL查詢的大小由參數max_packet_size(見here)決定。最新版本的限制爲1 GB。你應該能夠滿足18000行:

 select <n> union all 

成限制,很容易。天哪,我甚至不認爲它會是1兆字節。但我想說,通過應用程序傳遞18000個ID的列表似乎效率低下。如果一個數據庫可以從另一個數據庫中提取數據而不通過應用程序,那將會很不錯。

+0

此列表中包含像18K數字...很難做到這樣的事情。 – J33nn

+0

@ J33nn。 。 。然後將它們插入到表中並在查詢中使用該表。或者,因爲大多數列表都是由查詢生成的,只需將該查詢用作子查詢即可。 –

+0

查詢從外部腳本和不同的數據庫中生成。臨時表是我猜的最佳方法。但仍然可以採取更復雜的方式。 – J33nn

0

如果您設置的比較是巨大的,我建議你創建一個臨時表myids與僅列id,把那裏所有的18K值和運行查詢這樣的:

select id from myids where myids.id not in (select id from table1); 
+0

同意但如何使它更普遍和不那麼殘酷這是一個問題:) – J33nn

相關問題