返回不存在记录的id

时间:2014-05-12 08:55:26

标签: mysql sql

我有一系列ID:

[1, 2, 3, 4, 5, 6]

要检查表中存在哪些记录,我执行此查询:

SELECT id FROM table WHERE id in (1, 2, 3, 4, 5, 6);

查询返回每条现有记录的id,但如果我想知道哪些记录不存在,该怎么办?例如,如果不存在id: 1的记录,我希望返回此id。我怎么能这样做?

3 个答案:

答案 0 :(得分:4)

select idlist.id
from (
  select 1 as id
  union all select 2 
  union all select 3 
  union all select 4 
  union all select 5 
  union all select 6 
) as idlist
left join the_table
  on idlist.id = the_table.id
where the_table.id is null;

SQLFiddle示例:http://sqlfiddle.com/#!2/b3a5b/1

答案 1 :(得分:0)

select id from table where id not in(1,2,3,4,5,6)

答案 2 :(得分:0)

SELECT id FROM table WHERE id not in (1, 2, 3, 4, 5, 6);

返回ID不存在。