我有这个非常简单的目标,但我想不出任何简单的解决方案。我有一个来自用户输入的值列表,我想检查数据库中是否至少有一个值不存在。请注意,输入的值可以有重复项。
我的表:
| id | name |
| 0 | Bob |
| 1 | Ben |
| 2 | John |
| 3 | Rex |
用户输入的示例值:
1、2、2、4
不存在的值的计数,在本例中为 4,因此:
1
我可以做这样的事情:
select count(userInput.value)
from
(select 1 as value
union all
select 2
union all
select 2
union all
select 4) as userInput
left join myTable
on myTable.value = myTable.id
where myTable.id is null
上面的代码将计算 myTable 中所有不匹配的值(myTable.id 为空)。这会起作用,但我正在寻找一个不需要使用多个联合的简单解决方案。有人试过这样做吗?
编辑
这不起作用!
select count(myTable.id)
from myTable
where myTable.id not in(1,2,2,4)
上面的代码将计算输入值中不存在的 ID,这将导致 2,因为输入值中不存在 ID 0 和 3。请注意,预期输出为 1,因为值 4 是表中唯一不存在的值。