连接查询
1,交叉连接
select * from emp;查询单个表
select * from emp,dept;查询两个表
select * from emp cross join dept;
笛卡尔积
2,内连接
显示内连接,标准内连接
select * from emp as a inner join dept as b on a.dept_id = b.id;
隐式内连接,where 在结果集的基础上进行条件筛选
select * from emp as a ,dept as b where a.dept_id=b.id;
内连接 join
select * from emp as a join dept as b on a.dept_id = b.id;
内连接 cross join
select * from emp as a cross join dept as b on a.dept_id = b.id;
MySQL 里cross join on 和inner join on 结果一样
标准sql,cross join不能使用on,mysql支持on
特殊内连接,不等值内连接
select * from emp as a inner join dept as b on a.dept_id > b.id;
特殊内连接 自连接
select * from emp as a inner join emp as b on a.id =b.leader;
3,外连接
外连接显示的内容>=内连接
左外连接,左表为主表
select * from emp as a left outer join dept as b on a.dept_id = b.id;
右外连接,右表为主表
select * from emp as a right outer join dept as b on a.dept_id = b.id;
外连接,查询从表为空的数据
select * from emp as a left join dept as b on a.dept_id = b.id
where b.id is null;
on 和where的区别
on 两张表如何关联,where结果集做筛选
select * from emp as a left join dept as b on (a.dept_id = b.id and b.id is null);
on 优先where
select * from emp as a left join dept as b on a.dept_id = b.id where b.id is null;
4,全连接full ,unionq去重,union all不去重
select * from emp as a left join dept as b on a.dept_id = b.id
union
select * from emp as a right join dept as b on a.dept_id = b.id;