我有一个简单的JOIN问题
条件:
是否可以编写JOIN查询(不使用IF ... ELSE ...或CASE ... WHEN)返回结果,以便:
CREATE TABLE #A (number INT PRIMARY KEY)
INSERT INTO #A(number) VALUES(0)
INSERT INTO #A(number) VALUES(1)
INSERT INTO #A(number) VALUES(2)
INSERT INTO #A(number) VALUES(3)
INSERT INTO #A(number) VALUES(4)
INSERT INTO #A(number) VALUES(5)
INSERT INTO #A(number) VALUES(6)
INSERT INTO #A(number) VALUES(7)
INSERT INTO #A(number) VALUES(8)
INSERT INTO #A(number) VALUES(9)
CREATE TABLE #B (number INT PRIMARY KEY)
SELECT *
FROM #A
WHERE NOT EXISTS (SELECT number FROM #B)
UNION ALL
SELECT *
FROM #B
DROP TABLE #A
DROP TABLE #B
答案 0 :(得分:2)
获得所需结果的简单方法是:
SELECT *
FROM A
WHERE NOT EXISTS (SELECT 1 FROM B)
UNION ALL
SELECT *
FROM B
如果B
为空,则查询会返回所有A
条记录(来自UNION
操作的第一个查询)。
如果B
不为空,则仅返回此表的记录(来自UNION
操作的第二个查询)。