2

架构:

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;
4

4 回答 4

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
                  )
于 2013-04-25T15:32:23.917 回答
1

虚幻价值

SELECT *
FROM   #y
WHERE  coalesce(xKEY,-1) NOT IN 
                 (
                 SELECT *
                 FROM #exclGeoKeys
                 ) 
于 2013-04-27T20:10:40.567 回答
1

尝试使用左连接?

SELECT #y.*
FROM   #y
LEFT JOIN #exclGeoKeys excl on excl.xKEY = #y.xKEY
WHERE excl.xKEY IS NULL
于 2013-04-27T20:17:52.693 回答
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;

希望这可以帮助

于 2013-04-25T15:29:09.140 回答