連接查詢的分類 本文討論中用到的測試數(shù)據(jù) ``create table student( id int primary key auto_increment, name varchar(10) ); insert into student values (null,'xiaohong'), (null,'xiaoming'), (null,'xiaogang'), (null,'xiaoliang');
create table score( id int primary key auto_increment, stu_id int not null, score decimal(5,2) ); insert into score values (null,1,300.45), (null,2,400.35), (null,3,500);``
內(nèi)連接 inner join / join 由于mysql默認(rèn)是內(nèi)連接,所以,join 等同于 inner join 以兩個(gè)表舉例,內(nèi)連接只返回在連接過程中有連接匹配的記錄。也就是說,根據(jù)連接條件,兩個(gè)表中都有對(duì)應(yīng)的數(shù)據(jù)存在的記錄,才會(huì)返回。 舉例: select stu.id,stu.name,s.score from student as stu inner join score as s on stu.id = s.stu_id; 由于小亮沒有成績,所以小剛沒有出現(xiàn)在最終的結(jié)果中。
連接條件分析: 連接條件可以使用 on using where 區(qū)別:on 在連表查詢中,任何情況下都可以使用on,而且建議使用 on。on 是在連表的過程中,根據(jù)on條件判斷是否保留連表的結(jié)果。 using 是在連表查詢的字段名一致時(shí),可以使用。如 using(id)。using 條件中使用的字段,返回結(jié)果中只有一遍。 where 是在連表操作完成后,再根據(jù)where條件進(jìn)行數(shù)據(jù)過濾。不建議使用,因?yàn)檫@樣效率很低。
外連接 外連接查詢時(shí),允許另一方存在與之不匹配的數(shù)據(jù)。外連接的連接條件不可使用 where,須使用 on 或者 using其中的一種,其它都與內(nèi)連接一致。
左外連接(left outer join / left join): 左表為主表,即使右表沒有與左表匹配的記錄,也返回左表的記錄。而右表與左表不匹配的記錄將被忽略。 舉例: select * from student as stu left join score as s on stu.id = s.stu_id; 結(jié)果如下: +----+-----------+------+--------+--------+ | id | name | id | stu_id | score | +----+-----------+------+--------+--------+ | 1 | xiaohong | 1 | 1 | 300.45 | | 2 | xiaoming | 2 | 2 | 400.35 | | 3 | xiaogang | 3 | 3 | 500.00 | | 4 | xiaoliang | NULL | NULL | NULL | +----+-----------+------+--------+--------+
右外連接(right outer join / right join): 右表為主表,即使左表沒有與之匹配的記錄,也返回右表的記錄。 舉例: select * from score as s right join student as stu on s.stu_id=stu.id; +------+--------+--------+----+-----------+ | id | stu_id | score | id | name | +------+--------+--------+----+-----------+ | 1 | 1 | 300.45 | 1 | xiaohong | | 2 | 2 | 400.35 | 2 | xiaoming | | 3 | 3 | 500.00 | 3 | xiaogang | | NULL | NULL | NULL | 4 | xiaoliang | +------+--------+--------+----+-----------+
全外連接(full join):mysql 暫不支持,可以用union模擬實(shí)現(xiàn)。 自然連接 natural join (同 join) natural left join (同 left join) natural right join (同 right join) 自然連接會(huì)自動(dòng)判斷,以兩個(gè)表中相同的字段為連接條件,返回查詢結(jié)果。