SQL,如何转换为逻辑('not in'到'not exists')

时间:2013-11-06 17:25:27

标签: sql sql-server sql-server-2008

Delete From StudentTb Where StudentType in (1, 2) and StudentI not in
(
    Select lg.StudentI From StudentLog lg
)

我尝试将上面的代码更改为以下代码......但是,我不确定它是否正确。

Delete From StudentTb Where StudentType in (1, 2) 
    and Not Exists 
    (
        Select 'x' 
        From StudentLog lg                          
        Where StudentI= lg.StudentI
    )

有人可以帮助我吗?

3 个答案:

答案 0 :(得分:2)

Delete From StudentTb  s
Where StudentType in (1, 2) 
and Not Exists 
(
    Select *
    From StudentLog                          
    Where StudentI = s.StudentI
)

在子查询中,首先假定对列(未指定表名或别名)的非限定引用位于子查询本身中引用的表中,而不是外部查询中的其他表中。因此,在您的sql语法中,谓词Where StudentI = lg.StudentI的两侧都是StudentLog子查询表中的相同列。

答案 1 :(得分:2)

你所做的一切都没有在子查询中指定正确的别名:

Delete From StudentTb Where StudentType in (1, 2) 
    and Not Exists 
    (
        Select 'x' 
        From StudentLog lg                          
        Where StudentTb.StudentI= lg.StudentI
    )

注意 - select语句中的列不会影响最终结果,但仍然首选写*而不是'x'

答案 2 :(得分:1)

不存在且不存在并不总是具有相同的含义。我假设你想转换,因为“不在”往往会很慢。这是逻辑总是匹配的另一种方式。

Delete From StudentTb 
Where StudentType in (1, 2) 
and StudentI in
(
select StudentI
from StudentTb
except 
Select StudentI From StudentLog    
)