将SQL语句更改为EXISTS子句

问题描述 投票:0回答:1

给出以下SQL状态:

select 
    OBJECT_ID
FROM HPSFWY.RVERSIONING_1703 A 
WHERE A.STAMP_ID >1 
    AND A.OBJECT_REV NOT IN (
select MAX(OBJECT_REV)
from HPSFWY.RVERSIONING_1709763 B 
where B.COMMITID <= 6066 
    and B.OBJECT_ID = A.OBJECT_ID 
    ) 

在此查询中,where子句AND OBJECT_REV NOT IN必须从NOT IN更改为等效的EXISTS语句。

我们尝试这个

select 
OBJECT_ID
FROM HPSFWY.RVERSIONING_1703 A 
WHERE A.STAMP_ID >1 
AND exists (
select * 
from HPSFWY.RVERSIONING_1709763 B 
where B.COMMITID <= 6066 
and B.OBJECT_ID = A.OBJECT_ID 
and B.OBJECT_REV > A.OBJECT_REV) ;

它给我们带来接近的结果,但不尽相同

sql where-clause query-performance exists
1个回答
0
投票
您可以使用NOT EXISTS这样操作:

SELECT A.OBJECT_ID FROM HPSFWY.RVERSIONING_1703 A WHERE A.STAMP_ID > 1 AND NOT EXISTS ( SELECT 1 FROM ( SELECT MAX(B.OBJECT_REV) MAXOBJECT_REV FROM HPSFWY.RVERSIONING_1709763 B WHERE B.COMMITID <= 6066 AND B.OBJECT_ID = A.OBJECT_ID ) t WHERE t.MAXOBJECT_REV = A.OBJECT_REV )

注意:NOT IN的子查询:

select MAX(OBJECT_REV) from HPSFWY.RVERSIONING_1709763 B where B.COMMITID <= 6066 and B.OBJECT_ID = A.OBJECT_ID

仅返回1行和1列。因此,您可以像这样使用NOT IN代替<>

SELECT A.OBJECT_ID FROM HPSFWY.RVERSIONING_1703 A WHERE A.STAMP_ID > 1 AND A.OBJECT_REV <> ( SELECT MAX(OBJECT_REV) FROM HPSFWY.RVERSIONING_1709763 B WHERE B.COMMITID <= 6066 AND B.OBJECT_ID = A.OBJECT_ID )

© www.soinside.com 2019 - 2024. All rights reserved.