MySQL JOIN

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 |
+--------+------+---------+--------+

posted on 2019-08-23 12:31  doubtful  阅读(110)  评论(0编辑  收藏  举报

导航