Is there a logical difference between putting a condition in the ON clause of an inner join versus the where clause of the main query?

前端 未结 3 564
旧时难觅i
旧时难觅i 2021-01-06 03:33

Consider these two similar SQLs

(condition in ON clause)

select t1.field1, t2.field1
from
table1 t1 inner join table2 t2 on t1.id = t2.id and t1.bool         


        
3条回答
  •  -上瘾入骨i
    2021-01-06 04:33

    Both versions return the same data.

    Although this is true for an inner join, it is not true for outer joins.

    Stylistically, there is a third possibility. In addition to your two, there is also:

    select t1.field1, t2.field1
    from (select t1.*
          from table1 t1
          where t1.boolfield = 1
         ) t1 inner join
         table2 t2
        on t1.id = t2.id
    

    Which is preferable all depends on what you want to highlight, so you (or someone else) can later understand and modify the query. I often prefer the third version, because it emphasizes that the query is only using certain rows from the table -- the boolean condition is very close to where the table is specified.

    In the other two cases, if you have a long query, it can be problematic to figure out what "t1" really means. I think this is why some people prefer to put the condition in the ON clause. Others prefer the WHERE clause.

提交回复
热议问题