In SQL / MySQL, what is the difference between “ON” and “WHERE” in a join statement?

前端 未结 6 1935
臣服心动
臣服心动 2020-11-27 13:23

The following statements give the same result (one is using on, and the other using where):

mysql> select * from gifts INNER JOI         


        
6条回答
  •  悲哀的现实
    2020-11-27 13:53

    When using INNER JOIN, ON and WHERE will have the same result. So,

    select *
    from Table1 t1
    inner join Table2 t2 on t1.id = t2.id
    where t1.Name = 'John'
    

    will have the exact same output as

    select *
    from Table1 t1
    inner join Table2 t2 on t1.id = t2.id
        and t1.Name = 'John'
    

    As you have noted, this is not the case when using OUTER JOIN. What query plan gets built is dependent on the database platform as well as query specifics, and is subject to change, so making decisions on that basis alone is not going to give a guaranteed query plan.

    As a rule of thumb, you should use columns that join your tables in ON clauses and columns that are used for filtering in WHERE clauses. This provides the best readability.

提交回复
热议问题