gpt4 book ai didi

mysql - 从预定义列表中选择 NOT IN

转载 作者:行者123 更新时间:2023-11-29 02:22:49 24 4
gpt4 key购买 nike

为简单起见,假设我有一个表 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 中一步完成。

最佳答案

您可以使用包含 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 行,所以这对你的数据大小来说不是什么大问题。)

关于mysql - 从预定义列表中选择 NOT IN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28412965/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com