具有多个 Exists 但只有一个可以评估的 Oracle 过滤
Oracle filtering with multiple Exists but only one can evaluate
请考虑这个伪查询:
SELECT *
FROM A
WHERE
EXISTS (SELECT 1 FROM B WHERE B.ID = :ID)
OR EXISTS (SELECT 1 FROM C WHERE C.NAME = :NAME)
考虑一下:
- "From A" 复杂得多,我不想在那里做更多的连接。
- 我正在过滤结果和 foreach 记录 A 我只想 return 一行,这就是为什么我按照我希望他们评估的顺序存在;
如果第一个已经计算 "true",我如何避免 运行 第二个存在(由于性能)?
谢谢
您可以使用 case
表达式:
SELECT *
FROM A
WHERE
1 = CASE
WHEN EXISTS (SELECT 1 FROM B WHERE B.ID = :ID) THEN 1
WHEN EXISTS (SELECT 1 FROM C WHERE C.NAME = :NAME) THEN 1
END
这利用了 case
的 短路评估 行为,即 described in the documentation:
For a searched CASE
expression, the database evaluates each condition to determine whether it is true, and never evaluates a condition if the previous condition was true.
请考虑这个伪查询:
SELECT *
FROM A
WHERE
EXISTS (SELECT 1 FROM B WHERE B.ID = :ID)
OR EXISTS (SELECT 1 FROM C WHERE C.NAME = :NAME)
考虑一下:
- "From A" 复杂得多,我不想在那里做更多的连接。
- 我正在过滤结果和 foreach 记录 A 我只想 return 一行,这就是为什么我按照我希望他们评估的顺序存在;
如果第一个已经计算 "true",我如何避免 运行 第二个存在(由于性能)?
谢谢
您可以使用 case
表达式:
SELECT *
FROM A
WHERE
1 = CASE
WHEN EXISTS (SELECT 1 FROM B WHERE B.ID = :ID) THEN 1
WHEN EXISTS (SELECT 1 FROM C WHERE C.NAME = :NAME) THEN 1
END
这利用了 case
的 短路评估 行为,即 described in the documentation:
For a searched
CASE
expression, the database evaluates each condition to determine whether it is true, and never evaluates a condition if the previous condition was true.