给自己留档,基本是从这个博客抄来的。
例子:两个表格
表A:
id | name |
---|---|
1 | 张三 |
2 | 李四 |
3 | 王五 |
表B:
id | age |
---|---|
1 | 20 |
2 | 29 |
4 | 30 |
join
内关联,只返回两个表中关联上的结果
select a.id, a.name, b.age from a join b on a.id = b.id
得到结果:
a.id | a.name | b.age |
---|---|---|
1 | 张三 | 20 |
2 | 李四 | 29 |
left (outer) join
左外关联,关键字outer可省略。以left join关键字前面的表作为主表,和其他表进行关联,返回记录和主表的记录数一致,关联不上的字段置为null。
select a.id, a.name, b.age from a left join b on a.id = b.id
得到结果:
a.id | a.name | b.age |
---|---|---|
1 | 张三 | 20 |
2 | 李四 | 29 |
3 | 王五 | null |
right (outer) join
右外关联,关键字outer可省略。与left join相反,以right join关键字后面的表作为主表,和其他表进行关联,返回记录和主表的记录数一致,关联不上的字段置为null。
select a.id, a.name, b.age from a right join b on a.id = b.id
得到结果:
a.id | a.name | b.age |
---|---|---|
1 | 张三 | 20 |
2 | 李四 | 29 |
null | null | 30 |
full (outer) join
全外关联,关键字outer可省略。以两个表的记录为基准,返回两个表的记录去重之和,关联不上的字段为null。
select a.id, a.name, b.age from a full join b on a.id = b.id
得到结果:
a.id | a.name | b.age |
---|---|---|
1 | 张三 | 20 |
2 | 李四 | 29 |
3 | 王五 | null |
null | null | 30 |
left semi join
以left semi join关键字前面的表为主表,返回主表的KEY也在副表中的记录。
select a.name, b.name from a left semi join b on a.id = b.id
得到结果:
a.id | a.name |
---|---|
1 | 张三 |
2 | 李四 |
cross join
笛卡尔积关联,返回两个表的笛卡尔积结果,不需要指定关联键。
select a.id, a.name, b.age from a cross join b
得到结果:
a.id | a.name | b.age |
---|---|---|
1 | 张三 | 20 |
1 | 张三 | 29 |
1 | 张三 | 30 |
2 | 李四 | 20 |
2 | 李四 | 29 |
2 | 李四 | 30 |
3 | 王五 | 20 |
3 | 王五 | 29 |
3 | 王五 | 30 |