我正在尝试排除
中的名称列表我有表Names
id| Name | Surname
---------------------
1 | Michael | Kane
2 | Torben | Dane
3 | Dinge | Chain
4 | Django | Fain
5 | Juliett | Bravo
我有表Excludes
id| Name
-----------
1 | Michael
2 | Torben
现在我有两个问题:
SELECT * From Names, Excludes
WHERE Names.Name = Excludes.Name
GROUP BY Names.Name
导致
id | Name | Surname | id | Name
--------------------------------
1 | Michael | Kane | 1 |Michael
2 | Torben | Dane | 2 |Torben
现在,我想与!=
完全相反,以执行实际的purpouse并删除其中包含Michael
和Torben
名称的行
秒查询是:
SELECT * From Names, Excludes
WHERE Names.Name != Excludes.Name
GROUP BY Names.Name
结果
id | Name | Surname | id | Name
--------------------------------
3 | Dinge | Chain | 2 |Torben
4 | Django | Fain | 2 |Torben
5 | Juliett | Bravo | 2 |Torben
1 | Michael | Kane | 2 |Torben
2 | Torben | Dane | 1 |Michael
我想要的结果是
id| Name | Surname
---------------------
3 | Dinge | Chain
4 | Django | Fain
5 | Juliett | Bravo
我做错了什么?
答案 0 :(得分:5)
如果您要使用join
(而非not in
或not exists
),则需要left join
和where
条款:
SELECT n.*
From Names n LEFT JOIN
Excludes e
ON n.Name = e.Name
WHERE e.Name IS NULL;
一个简单的规则:从不在FROM
子句中使用逗号。
答案 1 :(得分:2)
改为使用left join
并过滤掉null
值:
SELECT Names.*
FROM Names
LEFT JOIN Excludes ON Names.Name = Excludes.Name
WHERE Excludes.Name IS NULL
group by
条款似乎毫无意义,所以我将其删除了。
另一种选择是将not exists
谓词与相关子查询一起使用:
SELECT * FROM Names n
WHERE NOT EXISTS
(SELECT Name FROM Excludes e WHERE e.Name = n.Name)
答案 2 :(得分:2)
select * from Names
where Name not in (select Name from Excludes)
答案 3 :(得分:1)
您可以在Excludes上使用(不在)内部查询,
select * from Names where Name not in (select Name from Excludes)