码迷,mamicode.com
首页 > 数据库 > 详细

MySQL JOIN

时间:2019-08-23 13:39:36      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:sele   ack   联合   ext   没有   左右   连接   out   inner   

MySQL JOIN

MySQL 中联合查询可以根据多个表中列的关系进行查询,查询效率较高
students 表:

+--------+------+
| stu_no | name |
+--------+------+
|      1 | Tom  |
|      2 | Jack |
+--------+------+

class 表:

+---------+--------+
| class   | stu_no |
+---------+--------+
| Math    |      1 |
| History |      3 |
+---------+--------+

INNER JOIN (内连接)

INNER JOIN 等于 JOIN
当左右表都存在匹配时返回行

SELECT * FROM students INNER JOIN class on students.stu_no = class.stu_no;
SELECT * FROM students JOIN class on students.stu_no = class.stu_no;

执行结果:

+--------+------+-------+--------+
| stu_no | name | class | stu_no |
+--------+------+-------+--------+
|      1 | Tom  | Math  |      1 |
+--------+------+-------+--------+

LEFT OUTER JOIN (左连接)

LEFT OUTER JOIN 等于 LEFT JOIN
返回左表所有行,如果右表没有匹配时,相应数据为 NULL

SELECT * FROM students LEFT OUTER JOIN class on students.stu_no = class.stu_no;
SELECT * FROM students LEFT JOIN class on students.stu_no = class.stu_no;

执行结果:

+--------+------+-------+--------+
| stu_no | name | class | stu_no |
+--------+------+-------+--------+
|      1 | Tom  | Math  |      1 |
+--------+------+-------+--------+
|      2 | Jack | NULL  |   NULL |
+--------+------+-------+--------+

RIGHT OUTER JOIN (右链接)

RIGHT OUTER JOIN 等于 RIGHT JOIN
返回右表所有行,如果左表没有匹配时,相应数据为 NULL

SELECT * FROM students RIGHT OUTER JOIN class on students.stu_no = class.stu_no;
SELECT * FROM students RIGHT JOIN class on students.stu_no = class.stu_no;

执行结果:

+--------+------+---------+--------+
| stu_no | name | class   | stu_no |
+--------+------+---------+--------+
|      1 | Tom  | Math    |      1 |
+--------+------+---------+--------+
|   NULL | NULL | History |      3 |
+--------+------+---------+--------+

FULL OUTER JOIN

返回左右表所有行,如果另一表没有匹配时,相应数据为 NULL
注意:MySQL 中没有 FULL OUTER JOIN, 需要使用以下代码代替

SELECT * FROM students LEFT OUTER JOIN class on students.stu_no = class.stu_no
UNION
SELECT * FROM students RIGHT OUTER JOIN class on students.stu_no = class.stu_no;

执行结果:

+--------+------+---------+--------+
| stu_no | name | class   | stu_no |
+--------+------+---------+--------+
|      1 | Tom  | Math    |      1 |
+--------+------+---------+--------+
|      2 | Jack | NULL    |   NULL |
+--------+------+---------+--------+
|   NULL | NULL | History |      3 |
+--------+------+---------+--------+

MySQL JOIN

标签:sele   ack   联合   ext   没有   左右   连接   out   inner   

原文地址:https://www.cnblogs.com/dbf-/p/11399288.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!