我有可能會存儲整數數十萬的表:從一組值中,我如何找到未存儲在表格列中的值?
desc id_key_table;
+----------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+-------+
| id_key | int(16) | NO | PRI | NULL | |
+----------------+--------------+------+-----+---------+-------+
從一個計劃,我有一個大的整數集。我想看看哪些整數不在上面的id_key列中。
到目前爲止,我想出了以下方法:
1)遍歷每個整數,執行:
select count(*) count from id_key_table where id_key = :id_key
當計數爲0的id_key從表中缺少。
這似乎是一個可怕的,可怕的方式來做到這一點。
2)創建一個臨時表,將每個值插入到臨時表中,然後對這兩個表執行JOIN。
create temporary table id_key_table_temp (id_key int(16) primary key);
insert into id_key_table_temp values (1),(2),(3),...,(500),(501);
select temp.id_key
from id_key_table_temp temp left join id_key_table as main
on temp.id_key = main.id_key
where main.killID is null;
drop table id_key_table_temp;
這似乎是最好的方法,但是,我敢肯定還有更好的方法,我還沒有想到。我寧願不必創建臨時表並使用一個查詢來確定哪些整數缺失。
是否有適合此類搜索的查詢?
(MySQL的)
第二種選擇是最好的。 (檢查速度的3種可能的寫法查詢方式,你編寫的'LEFT JOIN - IS NULL','NOT IN'版本和'NOT EXISTS'方式。通常MySQL中的第一或第三更快。 – 2011-05-11 16:56:44
我想你想檢查的id_keys不是順序的,(1-501)只是一個例子。 – 2011-05-11 16:58:13
ypercube,正確,密鑰不是順序的。實際上可能有非常大的差距:例如100000 - 150000填充缺失的隨機數,然後230000 - 400000填充缺失的隨機數等。 – Clinton 2011-05-11 17:39:05