我试图从表中获取一个唯一的值列表,该列表在其他2个表(多个表)的相应列中不存在
以下是我的表格外观:
----------- ----------- -----------
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”。类似地,表3的唯一值是“E,F”。
我使用以下查询:
select Value from Table1 where Table1.Value NOT IN (select Value from Table2);
知道如何扩展到2个表(或更多)?
由于
答案 0 :(得分:1)
使用and
:
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);
答案 1 :(得分:1)
你也可以在这里使用左连接:
SELECT t1.Value
FROM Table1 t1
LEFT JOIN Table2 t2
ON t1.Value = t2.Value
LEFT JOIN Table3 t3
ON t1.Value = t3.Value
WHERE
t2.Value IS NULL AND t2.Value IS NULL;