架构:
CREATE TABLE #exclGeoKeys (xKEY INT);
INSERT INTO #exclGeoKeys
values
(1),
(2);
CREATE TABLE #y (NAME CHAR(1),xKEY INT);
INSERT INTO #y
values
('A',1),
('C',2),
('D',NULL),
('E',3),
('F',4);
我可以缩短以下内容,以便产生相同的结果,而不需要OR xKEY IS NULL
部分吗?
SELECT *
FROM #y
WHERE xKEY NOT IN
(
SELECT *
FROM #exclGeoKeys
)
OR
xKEY IS NULL;
答案 0 :(得分:3)
使用NOT EXISTS运算符
选项SELECT *
FROM #y t
WHERE NOT EXISTS (
SELECT 1
FROM #exclGeoKeys t2
WHERE t.xKEY = t2.xKEY
)
SQLFiddle上的演示
EXISTS和EXCEPT运算符选项
SELECT *
FROM #y t
WHERE EXISTS (
SELECT t.xKEY
EXCEPT
SELECT t2.xKEY
FROM #exclGeoKeys t2
)
使用NOT EXISTS和INTERSECT运算符的选项
SELECT *
FROM #y t
WHERE NOT EXISTS (
SELECT t.xKEY
INTERSECT
SELECT t2.xKEY
FROM #exclGeoKeys t2
)
答案 1 :(得分:1)
试试这些:
--USING NOT EXISTS (DOES NOT REQUIRE THE IS NULL SECTION)
SELECT *
FROM #y AS T1
WHERE NOT EXISTS(SELECT * FROM #exclGeoKeys AS T2 WHERE T1.xKEY = T2.xKEY)
--OR T1.xKEY IS NULL;
--USING NOT IN
SELECT *
FROM #y AS T1
WHERE T1.xKEY NOT IN (SELECT T2.xKEY FROM #exclGeoKeys AS T2)
OR T1.xKEY IS NULL;
希望这有帮助
答案 2 :(得分:1)
虚幻价值
SELECT *
FROM #y
WHERE coalesce(xKEY,-1) NOT IN
(
SELECT *
FROM #exclGeoKeys
)
答案 3 :(得分:1)
试图使用左连接?
SELECT #y.*
FROM #y
LEFT JOIN #exclGeoKeys excl on excl.xKEY = #y.xKEY
WHERE excl.xKEY IS NULL