MySQL JOIN

Posted dbf-

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 |
+--------+------+---------+--------+

以上是关于MySQL JOIN的主要内容,如果未能解决你的问题,请参考以下文章

如何在 JOIN MySQL 中进行 GROUP BY 和 COUNT(*)

MySQL

mysql初学,mysql修改,mysql查找,mysql删除,mysql基本命令

mysql(设置/更改mysql密码,连接MySQL,MySQL常用命令,MySQL两种引擎区别)

MySQL教程

MySQL