我有两个sql server 2005表,如下所示:
Table A
varName varStatus
AGE Text
AGENDA Text
TEACH Text
Table B
varName varDesc
ACT Text
AGE Text
SAT Text
GPA Text
我需要一个或两个查询来获取两个表中不在两个表中的所有varNames。例如,上面的示例将使用:
Table A: AGENDA, TEACH
Table B: ACT, SAT, GPA
这是正确的,因为AGE是两个表中唯一出现的varname。
答案 0 :(得分:0)
此查询将为您提供A中的所有记录,但不包括B
SELECT A.* FROM
A LEFT JOIN B ON A.varName = B.varName
WHERE B.varName IS NULL
同样,此查询将为您提供B中的记录,但不会在A
中SELECT B.* FROM
A RIGHT JOIN B ON A.varName = B.varName
WHERE A.varName IS NULL
最后,你需要做的只是联合两个查询
SELECT A.* FROM
A LEFT JOIN B ON A.varName = B.varName
WHERE B.varName IS NULL
UNION
SELECT B.* FROM
A RIGHT JOIN B ON A.varName = B.varName
WHERE A.varName IS NULL
答案 1 :(得分:0)
如果变量可以在单个列表中,请使用UNION和NOT IN
SELECT 'A' AS sourceTable, varName
FROM tableA
WHERE varName NOT IN (SELECT varName FROM tableB)
UNION ALL
SELECT 'B' AS sourceTable, varName
FROM tableB
WHERE varName NOT IN (SELECT varName FROM tableA)
答案 2 :(得分:0)
(SELECT varName FROM tableA EXCEPT SELECT varName FROM tableB)
UNION
(SELECT varName FROM tableB EXCEPT SELECT varName FROM tableA)