一旦满足条件,是否可以让 SQL 停止检查 WHERE 子句?例如,如果我有如下声明:
SELECT * FROM Table1
WHERE Table1.SubID = (SELECT TOP 1 SubID FROM Table2 ORDER BY Date DESC)
OR Table1.OrderID = (SELECT TOP 1 OrderID FROM Table2 ORDER BY Date DESC)
是否可以在第一次检查后停止执行?本质上,应该只使用 where 子句中的两个检查中的一个,优先使用第一个。下面的例子。
示例案例:
情况1
Table1 SubID=600 OrderID=5
Table2 TOP 1 SubID=NULL
Table2 TOP 1 OrderID=5
Matches the OrderID to 5
案例2
Table1 SubId=600 OrderId=5
Table2 Top 1 SubID=600
Table2 Top 1 OrderID=3
Matches to SubID=600, not OrderID=3
给出建议的答案,awith
似乎是解决 SQL 本质上无法做到的最佳解决方案。对于我的具体情况,尝试将其放入 中时会出现问题outer apply
,如下所示。
SELECT * FROM tbl_MainFields
OUTER APPLY
(
WITH conditional AS
(
SELECT 1 AS 'choice', PlanCode, Carrier
FROM tbl_payers
WHERE tbl_payers.PlanCode =
(
SELECT TOP 1 PlanCode
FROM tbl_payerDenials
WHERE tbl_payerDenials.AccountNumber = tbl_mainFields.AccountNumber
ORDER BY InsertDate DESC
)
UNION ALL
SELECT 2 AS 'choice', PlanCode, Carrier
FROM tbl_payers
WHERE tbl_payers.OrderNum =
(
SELECT TOP 1 DenialLevel
FROM tbl_payerDenials
WHERE tbl_payerDenials.AccountNumber = tbl_mainFields.AccountNumber
ORDER BY InsertDate DESC
)
)
SELECT
PlanCode AS DenialPC,
Carrier AS DenialCAR
FROM conditional
WHERE choice = (SELECT MIN(choice) FROM conditional)
) denialData