What's the difference between where clause and on clause when table left join?

后端 未结 6 1573
深忆病人
深忆病人 2020-11-27 18:28

SQL1:

select t1.f1,t2.f2 
from t1 
   left join t2 on t1.f1 = t2.f2 and t1.f2=1 and t1.f3=0 

SQL2:

select t1.f1,t2.f2 
from         


        
6条回答
  •  醉话见心
    2020-11-27 19:13

    The relational algebra allows interchangeability of the predicates in the WHERE clause and the INNER JOIN, so even INNER JOIN queries with WHERE clauses can have the predicates rearrranged by the optimizer so that they may already be excluded during the JOIN process.

    I recommend you write the queries in the most readble way possible.

    Sometimes this includes making the INNER JOIN relatively "incomplete" and putting some of the criteria in the WHERE simply to make the lists of filtering criteria more easily maintainable.

    You can get more from this link: http://ask.sqlservercentral.com/questions/80067/sql-data-filter-condition-in-join-vs-where-clause

    For example, instead of:

    SELECT *
    FROM Customers c
    INNER JOIN CustomerAccounts ca
        ON ca.CustomerID = c.CustomerID
        AND c.State = 'NY'
    INNER JOIN Accounts a
        ON ca.AccountID = a.AccountID
        AND a.Status = 1
    

    Write:

    SELECT *
    FROM Customers c
    INNER JOIN CustomerAccounts ca
        ON ca.CustomerID = c.CustomerID
    INNER JOIN Accounts a
        ON ca.AccountID = a.AccountID
    WHERE c.State = 'NY'
        AND a.Status = 1
    

    But it depends, of course.

提交回复
热议问题