不存在不存在

时间:2015-03-19 16:28:17

标签: sql-server select

我有三张桌子

table1 -> xt1, yt1, zt1;
table2 -> xt2
table3 -> yt3, zt3


SELECT xt1, yt1, zt1  
From table1, table3 
Where  xt1
NOT IN
   (SELECT  DISTINCT table1.xt1 FROM table2 INNER JOIN table1 ON 
    table1.xt1 = Replace(table2.xt2,',','')) 
And table1.yt1 = table3.yt3
AND table1.zt1 = table3.zt3

它工作正常,但我需要很长时间。 如果我将Not IN替换为Not exists则返回空集。

SELECT xt1, yt1, zt1  
From table1, table3 
Where  Not exists 
(SELECT  DISTINCT table1.xt1 FROM table2 INNER JOIN table1 ON 
    table1.xt1 = Replace(table2.xt2,',','')) 
And table1.yt1 = table3.yt3
AND table1.zt1 = table3.zt3

第二个选择的结果应该是6行,但它返回notiong而不存在。

如果我试图将比较部分更改为 table1.xt1!=替换(table2.xt2,',','')并删除NOT IN  选择它会导致内存错误。

这是编写查询的最佳方式,以及为什么返回空集不存在 谢谢。

2 个答案:

答案 0 :(得分:2)

好的,首先,我将隐式连接更改为显式连接。然后我修复了NOT EXISTS,使其与外部table1

相关联
SELECT t1.xt1, t1.yt1, t1.zt1  
FROM table1 AS t1
INNER JOIN table3 AS t3
    ON t1.yt1 = t3.yt3
    AND t1.zt1 = t3.zt3
WHERE NOT EXISTS (  SELECT 1
                    FROM table2 AS t2
                    INNER JOIN table1 AS t1_1 
                        ON t1_1.xt1 = REPLACE(t2.xt2,',','')
                    AND t1_1.xt1 = t1.xt1) ;

可以进一步简化为:

SELECT t1.xt1, t1.yt1, t1.zt1  
FROM table1 AS t1
INNER JOIN table3 AS t3
    ON t1.yt1 = t3.yt3
    AND t1.zt1 = t3.zt3
WHERE NOT EXISTS (  SELECT 1
                    FROM table2 AS t2
                    WHERE t1.xt1 = REPLACE(t2.xt2,',','')
                 ) ;

答案 1 :(得分:0)

您需要选择IN或存在,具体取决于内部查询的大小。当存在外部查询和内部子查询时,如果子查询的结果很小,则优选In,因为基于子查询的结果选择外部查询。 如果子查询的结果很大,则首选存在,因为首先计算外部查询。