JOIN 按照功能大致分为如下三类:
A INNER JOIN B on 条件(内连接,或等值连接):获取两个表中字段匹配关系的记录。
A LEFT JOIN B on条件(左连接):获取左表所有记录,即使右表没有对应匹配的记录。
A RIGHT JOIN B on 条件(右连接): 与 LEFT JOIN 相反,用于获取右表所有记录,即使左表没有对应匹配的记录。
内连接查询
INNER JOIN子句的语法如下:SELECT column_list
FROM t1
INNER JOIN t2 ON join_condition1
INNER JOIN t3 ON join_condition2
...
WHERE where_conditions;
MySQL INNER JOIN支持使用等于以外的运算符,但是也可以使用大于(>),小于()运算符的其他运算符来形成连接谓词。
实例:
#两张表的数据如下:
mysql> select * from girl;
+-----+--------+
| hid | bname |
+-----+--------+
| 3 | 默默 |
| 2 | 羞羞 |
| 5 | 海燕 |
+-----+--------+
3 rows in set (0.00 sec)
mysql> select * from boy;+-----+--------+
| hid | bname |
+-----+--------+
| 1 | lisi |
| 2 | 王五 |
| 3 | 赵六 |
+-----+--------+
3 rows in set (0.00 sec)
#查询boy表和girl表中hid想同的bname。
mysql> select boy.hid,boy.bname,girl.hid,girl.bname
-> from
-> boy inner join girl on boy.hid=girl.hid;
+-----+--------+-----+--------+
| hid | bname | hid | bname |
+-----+--------+-----+--------+
| 3 | 赵六 | 3 | 默默 |
| 2 | 王五 | 2 | 羞羞 |
+-----+--------+-----+--------+
2 rows in set (0.01 sec)
#查询boy和girl表中数据,boy.hid=3的行.mysql> select boy.hid,boy.bname,girl.hid,girl.bname from boy inner join girl on boy.hid=girl.hid where boy.hid=3;
+-----+--------+-----+--------+
| hid | bname | hid | bname |
+-----+--------+-----+--------+
| 3 | 赵六 | 3 | 默默 |
+-----+--------+-----+--------+
1 row in set (0.00 sec)
#查询boy和girl表中数据,”boy.hid=girl.hid=3“的行.mysql> select boy.hid,boy.bname,girl.hid,girl.bname from boy inner join girl on boy.hid=girl.hid where boy.hid and girl.hid=3;
+-----+--------+-----+--------+
| hid | bname | hid | bname |
+-----+--------+-----+--------+
| 3 | 赵六 | 3 | 默默 |
+-----+--------+-----+--------+
1 row in set (0.00 sec)
注意:在匹配阶段 WHERE 子句的条件都不会被使用.仅在匹配阶段完成以后,WHERE 子句条件才会被使用。它将从匹配阶段产生的数据中检索过滤.
左连接查询
MySQL left join 与 join 有所不同,MySQL LEFT JOIN 会读取左边数据表的全部数据,即便右边表无对应数据.
实例:
#以左表所有的数据为准,查询右表所有的数据,匹配不到以"null"代替。
mysql> select boy.hid,boy.bname,girl.hid,girl.bname from boy left join girl on boy.hid=girl.hid;
+-----+--------+------+--------+
| hid | bname | hid | bname |
+-----+--------+------+--------+
| 3 | 赵六 | 3 | 默默 |
| 2 | 王五 | 2 | 羞羞 |
| 1 | lisi | NULL | NULL |
+-----+--------+------+--------+
3 rows in set (0.00 sec)
注意:如果 B 表中没有任何一行数据匹配 ON 的条件,将会额外生成一行所有列为 NULL 的数据。
右连接查询
MySQL RIGHT JOIN 会读取右边数据表的全部数据,即便左边边表无对应数据。
mysql> select boy.hid,boy.bname,girl.hid,girl.bname from boy right join girl on boy.hid=girl.hid;
+------+--------+-----+--------+
| hid | bname | hid | bname |
+------+--------+-----+--------+
| 2 | 王五 | 2 | 羞羞 |
| 3 | 赵六 | 3 | 默默 |
| NULL | NULL | 5 | 海燕 |
+------+--------+-----+--------+
3 rows in set (0.00 sec)
三种连接的区别: