使用学生表和成绩表来演示连接,SQL架构如下:
Create table If Not Exists student_info (id int, name varchar(255)); Create table If Not Exists student_score (id int, score int); Truncate table student_info; insert into student_info (id, name) values ('1', 'Wang'); insert into student_info (id, name) values ('2', 'Alice'); insert into student_info (id, name) values ('3', 'Allen'); Truncate table student_score; insert into student_score (id, score) values ('1', '65'); insert into student_score (id, score) values ('2', '70'); |
注意id为3的学生没有成绩记录,如下:
mysql> SELECT * FROM student_info; +------+-------+ | id | name | +------+-------+ | 1 | Wang | | 2 | Alice | | 3 | Allen | +------+-------+ 3 rows in set (0.00 sec) mysql> SELECT * FROM student_score; +------+-------+ | id | score | +------+-------+ | 1 | 65 | | 2 | 70 | +------+-------+ 2 rows in set (0.00 sec) |
执行一次典型的外连接查询,查询所有学生的成绩,不管其有没有成绩记录,如下:
mysql> SELECT * FROM student_info LEFT JOIN student_score ON student_info.id = student_score.id; +------+-------+------+-------+ | id | name | id | score | +------+-------+------+-------+ | 1 | Wang | 1 | 65 | | 2 | Alice | 2 | 70 | | 3 | Allen | NULL | NULL | +------+-------+------+-------+ 3 rows in set (0.00 sec) |
以下是关于外连接和ON的一些解释。
以左外连接为例,左外连接的目的是取出左表的每一行,然后和右表的所有行进行匹配,如果有符合ON条件的行,就输出组合后的结果,如果右表遍历后连没有一条符合ON条件的记录,就用NULL
值替代右表,再进行组合后输出。
如果ON条件设置为1,也就是无论左表的记录是什么,右表的所有行都符合条件,那么外连接的查询就和笛卡尔积是等价的,如下:
mysql> SELECT * FROM student_info LEFT JOIN student_score ON 1; +------+-------+------+-------+ | id | name | id | score | +------+-------+------+-------+ | 1 | Wang | 2 | 70 | | 1 | Wang | 1 | 65 | | 2 | Alice | 2 | 70 | | 2 | Alice | 1 | 65 | | 3 | Allen | 2 | 70 | | 3 | Allen | 1 | 65 | +------+-------+------+-------+ 6 rows in set (0.00 sec) |
在外连接中,ON子句是必需的,不能省略。比如左外连接,生成的结果集一定包含左表的所有行,而对于右表取哪些行,就通过ON子句来指定,注意这里的ON子句的结果已经不重要了,重要的是ON子句指定了右表如何匹配左表。
贴一张图以助于理解: