Difference between filtering queries in JOIN and WHERE?

前端 未结 3 615
后悔当初
后悔当初 2020-12-04 12:38

In SQL I am trying to filter results based on an ID and wondering if there is any logical difference between

SELECT value 
FROM table1 
JOIN table2 ON table1         


        
3条回答
  •  生来不讨喜
    2020-12-04 13:16

    While there is no difference when using INNER JOINS, as VR46 pointed out, there is a significant difference when using OUTER JOINS and evaluating a value in the second table (for left joins - first table for right joins). Consider the following setup:

    DECLARE @Table1 TABLE ([ID] int)
    DECLARE @Table2 TABLE ([Table1ID] int, [Value] varchar(50))
    
    INSERT INTO @Table1
    VALUES
    (1),
    (2),
    (3)
    
    INSERT INTO @Table2
    VALUES
    (1, 'test'),
    (1, 'hello'),
    (2, 'goodbye')
    

    If we select from it using a left outer join and put a condition in the where clause:

    SELECT * FROM @Table1 T1
    LEFT OUTER JOIN @Table2 T2
        ON T1.ID = T2.Table1ID
    WHERE T2.Table1ID = 1
    

    We get the following results:

    ID          Table1ID    Value
    ----------- ----------- --------------------------------------------------
    1           1           test
    1           1           hello
    

    This is because the where clause limits the result set, so we are only including records from table1 that have an ID of 1. However, if we move the condition to the on clause:

    SELECT * FROM @Table1 T1
    LEFT OUTER JOIN @Table2 T2
        ON T1.ID = T2.Table1ID
        AND T2.Table1ID = 1
    

    We get the following results:

    ID          Table1ID    Value
    ----------- ----------- --------------------------------------------------
    1           1           test
    1           1           hello
    2           NULL        NULL
    3           NULL        NULL
    

    This is because we are no longer filtering the result-set by the table1's ID of 1 - rather we are filtering the JOIN. So, even though table1's ID of 2 DOES have a match in the second table, it's excluded from the join - but NOT the result-set (hence the null values).

    So, for inner joins it doesn't matter, but you should keep it in the where clause for readability and consistency. However, for outer joins, you need to be aware that it DOES matter where you put the condition as it will impact your result-set.

提交回复
热议问题