SQL的四种连接查询
内连接
inner join 或者为 join
外连接
-
左连接 left join 或者 left outer join
-
右连接 right join 或者 right outer join
-
完全外连接 full join 或者 full outer join
创建数据库和数据表
– 创建数据库
create database testJoin;
– 创建两个表
— person表
id
name
cardId
create table person(
id int,
name varchar(20),
cardId int
);
— card 表
id
name
create table card(
id int,
name varchar(20)
);
往 card表中添加数据
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, '公交卡');
select * from person;
+------+--------+--------+
| id | name | cardId |
+------+--------+--------+
| 1 | 张三 | 1 |
| 2 | 李四 | 3 |
| 3 | 王五 | 6 |
+------+--------+--------+
person表中添加数据
insert into person values(1, '张三',1);
insert into person values(2, '李四',3);
insert into person values(3, '王五',6);
select * from card;
+------+-----------+
| id | name |
+------+-----------+
| 1 | 饭卡 |
| 2 | 建行卡 |
| 3 | 工商卡 |
| 4 | 农行卡 |
| 5 | 公交卡 |
+------+-----------+
– 没有创建外键。
1. inner join 或 join 查询: 内连接。
select * from person inner join card on person.cardId=card.id;
select * from person join card on person.cardId=card.id;
+------+--------+--------+------+-----------+
| id | name | cardId | id | name |
+------+--------+--------+------+-----------+
| 1 | 张三 | 1 | 1 | 饭卡 |
| 2 | 李四 | 3 | 3 | 工商卡 |
+------+--------+--------+------+-----------+
– 内联查询,两张表中的数据通过某个字段相对,查询出相关的记录。
2. left join(左外连接)
select * from person left join card on person.cardId=card.id;
select * from person left outer join card on person.cardId=card.id;
+------+--------+--------+------+-----------+
| id | name | cardId | id | name |
+------+--------+--------+------+-----------+
| 1 | 张三 | 1 | 1 | 饭卡 |
| 2 | 李四 | 3 | 3 | 工商卡 |
| 3 | 王五 | 6 | NULL | NULL |
+------+--------+--------+------+-----------+
– 左外连接,会把左边表里面的所有数据读取出来,而右边表的数据,如果相等,就显示
– 如果没有,就补空。
3. right join(右外连接)
select * from person right join card on person.cardId=card.id;
select * from person right outer join card on person.cardId=card.id;
+------+--------+--------+------+-----------+
| 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
— 使用左连接和右连接联合。
select * from person left join card on person.cardId=card.id
union
select * from person right join card on person.cardId=card.id;
+------+--------+--------+------+-----------+
| 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 | 公交卡 |
+------+--------+--------+------+-----------+