Difference between ON and WHERE clauses in SQL table joins

后端 未结 5 1448
小蘑菇
小蘑菇 2020-12-30 14:10
select e.last_name, e.hire_date
from employees e join employees m
on (m.last_name = \'Davies\')
and (e.hire_date > m.hire_date);

select e.last_name, e.hire_date
         


        
5条回答
  •  情书的邮戳
    2020-12-30 14:40

    Using on usually used for querying more than one table. When making that query, tables must have relationship each other, in general the same value in a specific fields.

    on will connect that same value, for example:

    **table1**:
    
    id_name   id_position   name
    1         1             john
    2         2             doe
    3         2             tom
    4         3             hawkins
    
    **table2**
    id_position   position
    1             system analyst
    2             programmer
    
    SELECT t1.id_name, t1.name, t2.position
      FROM table1 t1 LEFT JOIN table2 t2
      ON t1.id_position = t2.id_position
    
    -- RESULT:
    id_name   name     position
    1         john     system analyst
    2         doe      programmer
    3         tom      programmer
    4         hawkins  NULL            -- NO MATCH IN table 2
    

    as we can see on will connect table1 and table2 that have same value id_position, so it is a little different from what you have been written above.

    While where can be used in every query and not depends how many tables in that query. In general where is used for conditional thing that we want.

提交回复
热议问题