- 数据表
Join 用法
- inner join 内连接
- 两表必须有匹配的记录
select a.id,a.name,a.age,a.gender,b.likes,b.address from psn as a inner join psn2 as b on (a.id=b.id);
- left outer join 左外连接
- 左表显示全,不管右表是否有对应记录(有就正常显示,没有就是 Null)
select a.id,a.name,a.age,a.gender,b.likes,b.address from psn as a left outer join psn2 as b on (a.id=b.id);
- right outer join 右外连接
- 右表显示全,不管左表是否有对应记录(有就正常显示,没有就是 Null)
select a.id,a.name,a.age,a.gender,b.likes,b.address from psn as a right outer join psn2 as b on (a.id=b.id);
- full outer join 全部连接
- 左右都显示全,(有就正常显示,没有就是 Null)
select a.id,a.name,a.age,a.gender,b.likes,b.address from psn as a full outer join psn2 as b on (a.id=b.id);
- left semi join 左半连接
- 显示有匹配记录的左表(查询时右表字段不能有,右表会有很多重复记录)
select a.id,a.name,a.age,a.gender from psn as a left semi join psn2 as b on (a.id=b.id);
- cross join 交叉连接
- 两表行数的乘积后的行数,再根据条件过滤(实际数据过大时不推荐使用,非常慢)
select a.id,a.name,a.age,a.gender,b.likes,b.address from psn as a cross join psn2 as b on (a.id=b.id);
- Join 使用时需要注意
- ON 条件时,如果是多表多ON的时候,尽量让多个ON当中的字段相同
- sql 对 mr 的一种优化(尽量)
select a.val,b.val,c.val from a join b on (a.key=b.key1) join c on (c.key=b.key2)
# 两条语句差不同,但效率不一样
# 由于两个 on 的条件出现相同情况,所以 mr 时只会执行一个
select a.val,b.val,c.val from a join b on (a.key=b.key1) join c on (c.key=b.key1)