問題描述
SQL Server - 我有 3 個簡單的表(Fname、Lname 和 Exceptions),每一列都稱為 Name.我希望我的最終結果看起來像:(Fname 中的每個人 + LName 中的每個人)-(例外中的每個人).
SQL Server - I have 3 simple tables (Fname, Lname and Exceptions) with one column each called Name. I want my end result to look like: (Everybody in Fname + Everybody in LName) - (Everybody in Exceptions).
名稱:
Name
A
B
L 名稱:
Name
Y
Z
例外:
Name
A
Z
預期查詢結果集:
B
Y
當前 SQL 查詢:
Select Name from Fname
UNION ALL
Select Name from Lname
WHERE Name NOT IN
(Select Name from Exceptions)
SQL 查詢僅適用于刪除出現在 LName 中但不在 Fname 中的數據.有人可以幫忙嗎.
The SQL query only works on removing data which appears in LName but not in Fname. Can somebody please help.
推薦答案
UNION
的各個部分作為單獨的查詢處理,因此您可以將它們分組在子查詢中:
The parts of a UNION
are handled as separate queries, so you can group them in a subquery:
SELECT Name
FROM (Select Name from Fname
UNION ALL
Select Name from Lname)sub
WHERE Name NOT IN (Select Name from Exceptions)
如果您不關心重復,您可以將其保留為 UNION ALL
.
You can keep that as UNION ALL
if you don't care about duplicates.
這篇關于UNION ALL 和 NOT IN在一起的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!