首页 > 解决方案 > MySQL查询以查找表中不在列表中的ID

问题描述

我有一个大约 1000 个 id 的列表,其中只有少数 id 不在表中。我需要从列表中获取不在表中的 id。我无权创建表或将数据插入该表。

create table t1(id int);
insert into t1 values (1),(2),(3),(4),(5),(6),(7);

现在我需要获取不在表中但在 where 子句中的 id 的详细信息。

where clause - id in (2,5,8,9,25)

我的输出应该是 8,9,25

标签: mysqlsql

解决方案


不要把它们放在一个where子句中。使用具有left join或类似构造的派生表:

select i.id
from (select 2 as id union all
      select 5 as id union all
      select 8 as id union all
      select 9 as id union all
      select 25 as id
     ) i
where not exists (select 1 from t1 where t1.id = i.id);

推荐阅读