从预定义列表中选择NOT IN

时间:2015-02-09 15:13:39

标签: mysql sql

为简单起见,假设我有一个以transactions为主键的表id。目前表中只有10行,id为1到10。

我有一个ID列表:{9,10, 11 12 }。此列表未存储在数据库中。

我想在数据库中查询不在transactions表中的ID。在上面的例子中,我想得到11,12。

编写此查询的最佳方式是什么?

目前我只是查询SELECT * FROM transactions WHERE id IN (9,10,11,12)。并在代码中做我的交集。我想知道我可以在SQL中一步到位。

2 个答案:

答案 0 :(得分:2)

您可以使用包含ID的子查询执行此操作。这是一种方式:

select ids.id
from (select 9 as id union all select 10 union all select 11 union all select 12
     ) ids
where not exists (select 1 from transactions t where t.id = ids.id);

从名为transactions的表中返回行似乎效率低下 - 过多的数据会根据您的需要来回传递。 (虽然你只有10行,所以这对你的数据大小来说并不重要。)

答案 1 :(得分:0)

另一种方法是使用EXCEPT子句。例如;

select 9 as id union all select 10 union all select 11 union all select 12
except select id from transactions
相关问题