我试图从一个表中获取一个唯一的值列表,该列表不存在于其他 2 个表(多个表)的相应列中
这是我的 table 的样子:
----------- ----------- -----------
Table1 Table2 Table3
---|------- ---|------- ---|-------
id | Value id | Value id | Value
---|------- ---|------- ---|-------
1 | A 1 | A 1 | A
2 | B 2 | C 2 | D
3 | C 3 | D 3 | E
4 | D 4 | G 4 | F
现在,Table1 的唯一值为“B”(该值在 Table2 和 Tabl3 中不存在)。
表2的类似唯一值是“G”。同样,Table3 的唯一值是“E,F”。
我正在使用以下查询:
select Value from Table1 where Table1.Value NOT IN (select Value from Table2);
知道如何扩展到 2 个表(或更多)吗?
谢谢
最佳答案
使用和
:
select Value
from Table1
where Table1.Value not in (select Value from Table2) and
Table1.Value not in (select Value from Table3) ;
我不鼓励在子查询中使用NOT IN
。它的行为与您对 NULL
值的期望不同。如果子查询中的任何值为NULL
,则所有行都将被过滤掉。
相反,请使用NOT EXISTS
:
select t1.Value
from Table1 t1
where not exists (select 1 from table2 t2 where t2.value = t1.value) and
not exists (select 1 from table3 t3 where t3.value = t1.value);
关于mysql - 如何从表中获取多个表中不存在的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49621035/