一、四种连接
- 内连接: inner join & join(&表示或者)
- 外连接:
左连接:left join & left outer join
右连接:right join & right outer join
完全外连接:full outer join & full join
1.创建数据
数据库(testJoin)
person表(id, name, cardId)
card表(id, name)
create datebase testJoin;
create table person(id int, name varchar(20), cardId int);
create table card(id int, name varchar(20));
添加数据
insert into card values(1,'饭卡');
insert into card values(2,'建行卡');
insert into card values(3,'农行卡');
insert into card values(4,'工商卡');
insert into card values(5,'邮政卡');
insert into person values(1,'张三',1);
insert into person values(2,'李四',3);
insert into person values(3,'王五',6);
(1)内联查询(inner join)
内连接查询就是两张表中的数据,通过某个字段相等,查询出相关记录数据,用 on… 表示条件,其中的inner join 可以用 join代替。
select * from person join card on person.cardId = card.id;
-- result
+------+------+--------+------+--------+
| id | name | cardId | id | name |
+------+------+--------+------+--------+
| 1 | 张三 | 1 | 1 | 饭卡 |
| 2 | 李四 | 3 | 3 | 农行卡 |
+------+------+--------+------+--------+
上述操作也可以使用下列语句代替:
```sql
select * from person,card where person.cardId = card.id;
(2)左外连接
左外连接,会把左边表里面的所有数据取出来,而右边表数据如果有相等的,就显示出来,如果没有,就补 NULL
select * from person left join card on person.cardId = card.id;
-- result
+------+------+--------+------+--------+
| id | name | cardId | id | name |
+------+------+--------+------+--------+
| 1 | 张三 | 1 | 1 | 饭卡 |
| 2 | 李四 | 3 | 3 | 农行卡 |
| 3 | 王五 | 6 | NULL | NULL |
+------+------+--------+------+--------+
(3)右连接
与left join相反,显示右边所有的数据,左边的数据如果没用就显示空。
select * from person right join card on person.cardId = card.id;
-- result
+------+------+--------+------+--------+
| id | name | cardId | id | name |
+------+------+--------+------+--------+
| 1 | 张三 | 1 | 1 | 饭卡 |
| NULL | NULL | NULL | 2 | 建行卡 |
| 2 | 李四 | 3 | 3 | 农行卡 |
| NULL | NULL | NULL | 4 | 工商卡 |
| NULL | NULL | NULL | 5 | 邮政卡 |
+------+------+--------+------+--------+
(4) full join(全外连接)
select * from person full join card on person.cardId = card.id;
报错,因为Mysql不支持full join
四种连接的示意图如下:
inner join.png
left join.png
right join.png
full join.png
可以看到,全连接相当于左右连接合并。因此,我们使用Union.
select * from person left join card on person.cardId = card.id
union
select * from person right join card on person.cardId = card.id;
-- result
+------+------+--------+------+--------+
| id | name | cardId | id | name |
+------+------+--------+------+--------+
| 1 | 张三 | 1 | 1 | 饭卡 |
| 2 | 李四 | 3 | 3 | 农行卡 |
| 3 | 王五 | 6 | NULL | NULL |
| NULL | NULL | NULL | 2 | 建行卡 |
| NULL | NULL | NULL | 4 | 工商卡 |
| NULL | NULL | NULL | 5 | 邮政卡 |
+------+------+--------+------+--------+
网友评论