SQL Server LEFT JOIN中的OR子句导致高逻辑读取

时间:2017-08-09 15:17:34

标签: sql sql-server

如何通过消除OR子句重写以下查询

SELECT T1.Name, T1.Value-T2.value as value 
FROM TABLE1 T1 LEFT JOIN TABLE2 T2 ON T2.ID=T1.ID OR T2.OLD_ID=T1.ID

3 个答案:

答案 0 :(得分:3)

这是对原始问题的回答。

OR会导致连接中出现重大问题。您可以非常轻松地修复此查询。基本上,这应该做你想要的:

SELECT T1.*
FROM TABLE1 T1;

为什么呢?您没有从第二个表中选择任何行,LEFT JOIN会保留第一个表中的所有行。有可能重复行,但我猜你不需要重复(我的假设)。

答案 1 :(得分:0)

请尝试IN

SELECT T1.name, T1.value - T2.value AS value
FROM TABLE1 T1
LEFT JOIN TABLE2 T2 ON T1.ID IN (T2.ID, T2.OLD_ID)

修改

另一个版本,包含多个LEFT JOIN s:

SELECT T1.name, T1.value - COALESCE(T2A.value, T2B.value) AS value
FROM TABLE1 T1
LEFT JOIN TABLE2 T2A ON T1.ID = T2.ID
LEFT JOIN TABLE2 T2B ON T1.ID = T2.OLD_ID

又一个版本:

SELECT T1.name, T1.value - T2.value AS value
FROM TABLE1 T1
LEFT JOIN ( SELECT ID, value FROM TABLE2 UNION
            SELECT OLD_ID, value FROM TABLE2 ) T2 ON T1.ID = T2.ID

答案 2 :(得分:0)

这是写它的另一种方法,但我不知道是否会影响逻辑读取:

SELECT T1.Name, T1.Value-T2.value as value 
FROM TABLE1 T1 
LEFT JOIN TABLE2 T2 
 ON T2.ID=T1.ID 
UNION ALL 
SELECT T1.Name, T1.Value-T2.value as value 
FROM TABLE1 T1 
LEFT JOIN TABLE2 T2 
 ON T2.ID<>T1.ID
 AND T2.OLD_ID=T1.ID