新聞中心
連接查詢的分類
本文討論中用到的測試數(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');
創(chuàng)新互聯(lián)是一家專業(yè)提供煙臺企業(yè)網(wǎng)站建設(shè),專注與做網(wǎng)站、成都網(wǎng)站建設(shè)、H5頁面制作、小程序制作等業(yè)務(wù)。10年已為煙臺眾多企業(yè)、政府機構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)絡(luò)公司優(yōu)惠進行中。
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
以兩個表舉例,內(nèi)連接只返回在連接過程中有連接匹配的記錄。也就是說,根據(jù)連接條件,兩個表中都有對應(yīng)的數(shù)據(jù)存在的記錄,才會返回。
舉例: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 是在連表查詢的字段名一致時,可以使用。如 using(id)。using 條件中使用的字段,返回結(jié)果中只有一遍。
where 是在連表操作完成后,再根據(jù)where條件進行數(shù)據(jù)過濾。不建議使用,因為這樣效率很低。
外連接
外連接查詢時,允許另一方存在與之不匹配的數(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模擬實現(xiàn)。
自然連接
natural join (同 join)
natural left join (同 left join)
natural right join (同 right join)
自然連接會自動判斷,以兩個表中相同的字段為連接條件,返回查詢結(jié)果。
注意:內(nèi)連接不寫連接條件會出現(xiàn)笛卡爾積的結(jié)果,應(yīng)該避免這種情況,而外連接不寫連接條件會報錯
當(dāng)前題目:mysql連接查詢(俗稱連表查詢)內(nèi)連接、外連接、自然連接
網(wǎng)頁地址:http://ef60e0e.cn/article/gchsoj.html