溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

mysql 連接查詢(俗稱連表查詢)內(nèi)連接、外連接、自然連接

發(fā)布時間:2020-08-03 02:29:09 來源:網(wǎng)絡(luò) 閱讀:3011 作者:梧桐深院 欄目:MySQL數(shù)據(jù)庫

連接查詢的分類

本文討論中用到的測試數(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);``

mysql 連接查詢(俗稱連表查詢)內(nèi)連接、外連接、自然連接

內(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;
mysql 連接查詢(俗稱連表查詢)內(nèi)連接、外連接、自然連接
如上圖所示,由于小亮沒有成績,所以小剛沒有出現(xiàn)在最終的結(jié)果中。

連接條件分析:

連接條件可以使用 on using where
區(qū)別:on 在連表查詢中,任何情況下都可以使用on,而且建議使用 on。on 是在連表的過程中,根據(jù)on條件判斷是否保留連表的結(jié)果。
using 是在連表查詢的字段名一致時,可以使用。如 using(id)。using 條件中使用的字段,返回結(jié)果中只有一遍。
where 是在連表操作完成后,再根據(jù)where條件進(jìn)行數(shù)據(jù)過濾。不建議使用,因?yàn)檫@樣效率很低。

外連接

外連接查詢時,允許另一方存在與之不匹配的數(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)

自然連接會自動判斷,以兩個表中相同的字段為連接條件,返回查詢結(jié)果。

注意:內(nèi)連接不寫連接條件會出現(xiàn)笛卡爾積的結(jié)果,應(yīng)該避免這種情況,而外連接不寫連接條件會報錯

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI