LEFT JOIN Significantly faster than INNER JOIN

后端 未结 2 1628
鱼传尺愫
鱼传尺愫 2021-02-07 01:03

I have a table (MainTable) with a bit over 600,000 records. It joins onto itself via a 2nd table (JoinTable) in a parent/child type relationship:

相关标签:
2条回答
  • 2021-02-07 01:48

    The Left join seems to be faster because SQL is forced to do the smaller select first and then join to this smaller set of records. For some reason the optimiser doesn't want to do this naturally.

    3 ways to force the joins to happen in the right order:

    1. Select the first subset of data into a temporary table (or table variable) then join on it
    2. Use left joins (and remember that this could return different data because it's a left join not an inner join)
    3. use the FORCE ORDER keyword. Note that if table sizes or schemas change then the query plan may not be correct (see https://dba.stackexchange.com/questions/45388/forcing-join-order)
    0 讨论(0)
  • 2021-02-07 01:58

    Try this one. Same result, different approach:

    SELECT c.ID, p.ID 
    FROM
    (SELECT   Child.ID, JoinTable.ParentID
    FROM     MainTable
    AS       Child
    JOIN     JoinTable
          ON Child.ID = JoinTable.ID) AS c
    INNER JOIN 
    (SELECT   Parent.ID, JoinTable.ID
    FROM     MainTable
    AS       Parent
    JOIN     JoinTable
          ON Parent.ID = JoinTable.ParentID
         AND Parent.SomeOtherData = Child.SomeOtherData) AS p
    ON c.ParentID = p.ID
    

    If it does not help, use cte:

    ;WITH cte AS
    (SELECT   Child.ID, JoinTable.ParentID
    FROM     MainTable
    AS       Child
    JOIN     JoinTable
          ON Child.ID = JoinTable.ID)
    SELECT cte.ID, Parent.ID
    FROM cte INNER JOIN 
    MainTable
    AS       Parent
          ON Parent.ID = cte.ParentID
         AND Parent.SomeOtherData = cte.SomeOtherData
    
    0 讨论(0)
提交回复
热议问题