我有2个这样的表:
Table1:
animal name color
cat bob red
dog bill blue
Table2:
animal name
cat bob
fish joe
我想查询表1中的所有数据,除非它们具有表2中的唯一标识,因此我会得到蓝色的狗账单,而不是猫,因为它出现在表2中。
我做了:
select t.animal, t.name, t.color
from Table1 as t, Table2 as t2
where NOT(t.animal = t2.animal AND
t.name = t2.name)
group by t.animal, t.name
有更有效的方法吗?
答案 0 :(得分:2)
select t.animal, t.name, t.color
from Table1 as t
LEFT JOIN Table2 as t2 ON t.animal = t2.animal and t.name = t2.name
where table2.name is null
group by t.animal, t.name
答案 1 :(得分:1)
一个简单的where not exists
子句可以解决这个问题:
select t1.animal, t1.name, t1.color
from Table1 t1
where not exists
(
select 1
from Table2 t2
where t2.animal = t1.animal
and t2.name = t1.name
)
您还可以使用反连接模式:
select t1.animal, t1.name, t1.color
from Table1 t1
left outer join Table2 t2 on t1.animal = t2.animal and t1.name = t2.name
where t2.animal is null
答案 2 :(得分:-1)
SELECT * FROM table_one t1
WHERE t1.animal NOT IN
(SELECT animal FROM table_two)