一、 JOIN 按照功能大致分为如下三类:
- INNER JOIN(内连接,或等值连接):获取两个表中字段匹配关系的记录。
- LEFT JOIN(左连接):获取左表所有记录,即使右表没有对应匹配的记录。
- RIGHT JOIN(右连接): 与 LEFT JOIN 相反,用于获取右表所有记录,即使左表没有对应匹配的记录。
二、join 使用实例
1、准备两张表
mysql> select * from person; +----+------+------+ | id | name | age | +----+------+------+ | 3 | Mili | 21 | | 4 | tom | 19 | | 5 | mike | 18 | | 6 | aaa | 17 | | 7 | bbb | 16 | | 8 | ccc | 22 | | 9 | ddd | 23 | | 10 | eee | 25 | +----+------+------+ 8 rows in set (0.00 sec)
mysql> select * from account; +----+---------+ | id | account | +----+---------+ | 1 | 22 | | 2 | 23 | | 3 | 11 | | 4 | 12 | | 5 | 13 | | 6 | 666 | +----+---------+ 6 rows in set (0.00 sec)
inner join 用法(内连接)以及实例:
mysql> select a.*,b.* from person a inner join account b on a.id=b.id; // select * from person a,account b where a.id=b.id;与左侧的inner join效果一样; +----+------+------+----+---------+ | id | name | age | id | account | +----+------+------+----+---------+ | 3 | Mili | 21 | 3 | 11 | | 4 | tom | 19 | 4 | 12 | | 5 | mike | 18 | 5 | 13 | | 6 | aaa | 17 | 6 | 666 | +----+------+------+----+---------+ 4 rows in set (0.00 sec) 获取person表和account表中id都有的数据,只要其中一表中无都不会匹配出。
left join 用法(外连接):
mysql> select a.*,b.* from person a left join account b on a.id=b.id; +----+------+------+------+---------+ | id | name | age | id | account | +----+------+------+------+---------+ | 3 | Mili | 21 | 3 | 11 | | 4 | tom | 19 | 4 | 12 | | 5 | mike | 18 | 5 | 13 | | 6 | aaa | 17 | 6 | 666 | | 7 | bbb | 16 | NULL | NULL | | 8 | ccc | 22 | NULL | NULL | | 9 | ddd | 23 | NULL | NULL | | 10 | eee | 25 | NULL | NULL | +----+------+------+------+---------+ 8 rows in set (0.00 sec) 以left左边表为主表来关联查询出数据,即使left右边的表中无也会查询。
right join 用法(外连接):
mysql> select a.*,b.* from person a right join account b on a.id=b.id; +------+------+------+----+---------+ | id | name | age | id | account | +------+------+------+----+---------+ | NULL | NULL | NULL | 1 | 22 | | NULL | NULL | NULL | 2 | 23 | | 3 | Mili | 21 | 3 | 11 | | 4 | tom | 19 | 4 | 12 | | 5 | mike | 18 | 5 | 13 | | 6 | aaa | 17 | 6 | 666 | +------+------+------+----+---------+ 6 rows in set (0.00 sec) 以right 右边表为主表来关联查询出数,即使左边表中无也会查询出。