Can UNION ALL be faster than JOINs or do my JOINs just suck?

后端 未结 5 1030
旧时难觅i
旧时难觅i 2020-12-18 10:19

I have a Notes table with a uniqueidentifier column that I use as a FK for a variety of other tables in the database (don\'t worry, the uniqu

相关标签:
5条回答
  • 2020-12-18 10:27

    UNION is slower, but UNION ALL should be pretty quick, right?

    0 讨论(0)
  • 2020-12-18 10:28

    I may be wrong, but I think that you will get a better performance if you rewrite you JOIN version to

    SELECT N.*  
    FROM Notes N  
    LEFT JOIN Leads L ON N.TargetUniqueID = L.UniqueID AND L.LeadID = @LeadID  
    LEFT JOIN Quotes Q ON N.TargetUniqueID = Q.UniqueID  AND Q.LeadID = @LeadID
    WHERE Q.LeadID IS NOT NULL OR L.LeadID IS NOT NULL
    
    0 讨论(0)
  • 2020-12-18 10:29

    The UNION ALL version would probably be satisfied quite easily by 2 index seeks. OR can lead to scans. What do the execution plans look like?

    Also have you tried this to avoid accessing Notes twice?

    ;WITH J AS
    (
    SELECT UniqueID FROM Leads WHERE LeadID = @LeadID
    UNION ALL
    SELECT UniqueID FROM Quotes WHERE LeadID = @LeadID
    )
    
    SELECT N.*  /*Don't use * though!*/
    FROM Notes N  
    JOIN J ON N.TargetUniqueID = J.UniqueID  
    
    0 讨论(0)
  • 2020-12-18 10:33

    In my experience, SQL Server is really bad with join conditions containing OR. I also use UNIONs in that case, and I got similar results like you (maybe half a second instead of 20).

    Who said UNIONS are bad? Especially if you use UNION ALL, there should not be a performance hit, as UNION would have to go through the result to only keep unique records (actually doing something like distinct or group by).

    0 讨论(0)
  • 2020-12-18 10:45

    You second query wouldn' even give correct results as it would covert the left joins to inner joins, see here for explantion as to why your syntax is bad:

    http://wiki.lessthandot.com/index.php/WHERE_conditions_on_a_LEFT_JOIN

    0 讨论(0)
提交回复
热议问题