简体   繁体   中英

OR Clause in SQL Server LEFT JOIN causing high logical reads

How can I rewrite the below query by eliminating the OR clause

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

THIS ANSWERS THE ORIGINAL QUESTION.

OR causes major problems in joins. You can very easily fix this query. Basically, this should do what you want:

SELECT T1.*
FROM TABLE1 T1;

Why? You are selecting no rows from the second table and the LEFT JOIN keeps all rows in the first table. There is the possibility of duplicate rows, but I'm guessing that you don't want duplicates (an assumption on my part).

Try IN instead:

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)

Edit

Another version, with multiple 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

Yet another version:

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

Here is another way to write it, though I don't know if will affect the logical reads:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM