left join,right join,inner join 的用法

[参考mysql官方文档]

left join:左联查询(属于外联查询), 以左表为准,若右表不存在相关记录,显示NULL。
right join:右联查询 (属于外联查询)以右表为准,若左表不存在相关记录,显示NULL。
inner join:内联查询(inner可选),两张表中符合联接关系的记录。

举例如下:

create table tb1(
    tb1_id int primary key auto_increment,
    tb1_name varchar(64) default '');
create table tb2(
    tb2_id int primary key auto_increment,
    tb2_name varchar(64) default '');

insert into tb1 values(1, 'tb1_name1'), 
                      (2, 'tb1_name2'), 
                      (3, 'tb1_name3'),
                      (4, 'tb1_name4'), 
                      (5, 'tb1_name5');
insert into tb2 values(1, 'tb2_name1'),
                      (2, 'tb2_name2'),
                      (3, 'tb2_name3'), 
                      (4, 'tb2_name4'), 
                      (8, 'tb2_name8'), 
                      (9, 'tb2_name9');

mysql> select * from tb1 join tb2 on tb1.tb1_id=tb2.tb2_id;
mysql> select * from tb1 inner join tb2 on tb1.tb1_id=tb2.tb2_id;
+--------+-----------+--------+-----------+
| tb1_id | tb1_name  | tb2_id | tb2_name  |
+--------+-----------+--------+-----------+
|      1 | tb1_name1 |      1 | tb2_name1 |
|      2 | tb1_name2 |      2 | tb2_name2 |
|      3 | tb1_name3 |      3 | tb2_name3 |
|      4 | tb1_name4 |      4 | tb2_name4 |
+--------+-----------+--------+-----------+

mysql> select * from tb1 left join tb2 on tb1.tb1_id=tb2.tb2_id;
+--------+-----------+--------+-----------+
| tb1_id | tb1_name  | tb2_id | tb2_name  |
+--------+-----------+--------+-----------+
|      1 | tb1_name1 |      1 | tb2_name1 |
|      2 | tb1_name2 |      2 | tb2_name2 |
|      3 | tb1_name3 |      3 | tb2_name3 |
|      4 | tb1_name4 |      4 | tb2_name4 |
|      5 | tb1_name5 |   NULL | NULL      |
+--------+-----------+--------+-----------+


mysql> select * from tb1 right join tb2 on tb1.tb1_id=tb2.tb2_id;
+--------+-----------+--------+-----------+
| tb1_id | tb1_name  | tb2_id | tb2_name  |
+--------+-----------+--------+-----------+
|      1 | tb1_name1 |      1 | tb2_name1 |
|      2 | tb1_name2 |      2 | tb2_name2 |
|      3 | tb1_name3 |      3 | tb2_name3 |
|      4 | tb1_name4 |      4 | tb2_name4 |
|   NULL | NULL      |      8 | tb2_name8 |
|   NULL | NULL      |      9 | tb2_name9 |
+--------+-----------+--------+-----------+

你可能感兴趣的:(JOIN,JOIN,JOIN,mysql,right,inner,left)