gpt4 book ai didi

MySQL查询以查找表中不存在的ID

转载 作者:行者123 更新时间:2023-11-29 05:10:47 32 4
gpt4 key购买 nike

我有一个预先生成的 ID 列表,我需要检查它是否存在于表中。我的表有两列,idname,其中 id 是一个自动递增的整数,name 是一个 varchar(255)

我基本上想从我的预生成列表中计算出表 foo 中不存在的 ID 数量。假设我的列表中有数字 510,最好的写法是:

从 foo 中选择 count(*) where id does not exist in ( 5, 10 )

这里的想法是,如果 5 和 10 不存在,我需要响应 2,而不是 foo 中没有 id 5 或 10。

最佳答案

TL; DR 示例数据和查询 at rextester

The idea here is that if 5 and 10 do not exist, I need the response 2, and not the number of rows in foo that do not have the id 5 or 10.

您应该提供更多信息以避免混淆。

例子

id | name
1 | tom
2 | joe
3 | mae
4 | goku
5 | vegeta

如果您的列表包含 (1, 2, 3) 那么您的答案应该是 0(因为所有三个都在表中)

如果您的列表包含 (1, 2, 6) 那么您的答案应该是 1。(因为 1 和 2 在表中但 6 不在)

如果您的列表包含 (1, 6, 7) 那么您的答案应该是 2。

如果您的列表包含 (6, 7, 8) 那么您的答案应该是 3。

assuming this was your question

如果你知道列表的长度

select 2 - count(*) as my_count from foo where id in (5, 10)

以下查询告诉您 foo 中有多少个。

select count(*) from foo where id in (5,10) 

所以如果你想找到那些不存在的,从你的列表的长度中减去这个结果。

select n - count(*) as my_count from foo where id in (5, 10,....)

关于MySQL查询以查找表中不存在的ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39668249/

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