left join on和where

left join on:

向左关联某个表记录,意思是以左边的表记录为基准,通过关联条件会从左表返回所有的行,即使在右表中没有匹配的行。

举个例子:

select * from A left join B on A.id=B.id

说明:从A表左外联接B表,基于A.id=B.id

 

和where的区别:

1.on条件是生成临时表的条件,不管on中的条件是否成真,都会返回左边表中的记录(为null显示)。

2.where条件是建立在临时表生成好基础上再对临时表过滤的条件,已经没有left join的含义(必须返回左边表的记录),条件不符合就全部过滤。

 

假设两张表,

表1-tab1:     表2-tab2:

id name       name class

1  10        10  AA

2  20        20  BB

3  30        20  CC

 

SQL语句:

1.select * from tab1 left join tab2 on (tab1.name=tab2.name) where tab2.class='AA'

2.select * from tab1 left join tab2 on (tab1.name=tab2.name and tab2.class='AA')

SQL1结果:

1.on的条件为tab1.name=tab2.name,以tab1表为基准,返回所有的值

tab1.id  tab1.name  tab2.name  tab2.class

1       10       10       AA

2       20       20       BB

2       20       20       CC

3       30       NULL     NULL 

2.WHERE后的条件tab2.class='AA',查询结果为

tab1.id  tab1.name  tab2.name  tab2.class

1       10       10       AA

SQL2结果:

on的条件为tab1.name=tab2.name and tab2.class='AA',以tab1表为基准返回所有的值

tab1.id  tab1.name  tab2.name  tab2.class

1       10       10       AA

2       20      NULL     NULL

3       30      NULL      NULL 

 

比较以下sql区别:

查询有课程成绩小于60分的同学的学号、姓名,

 

--以student_id分组:

SELECT student_id,sname FROM test_score s,test_student t WHERE s.num<'60' AND s.student_id=t.sid GROUP BY student_id;

--按student_id去重:

SELECT DISTINCT student_id,sname FROM test_score s,test_student t WHERE s.num<'60' AND s.student_id=t.sid;

--以left join左连接

SELECT DISTINCT student_id,sname FROM test_student t LEFT JOIN test_score s ON s.student_id=t.sid WHERE s.num<'60';

posted @ 2018-01-24 14:26  shenyin  阅读(481)  评论(0编辑  收藏  举报