一、多表查询
sql
复制代码
#多表查询 笛卡尔积
select * from emp , dept where emp.dept_id = dept.id ;
二、内连接
sql
复制代码
#隐藏式连接
Select emp.name , dept.name from emp,dept where emp.dept_id = dept.id;
#起别名
Select e.name, d.name from emp e,dept d where e.dept_id = d.id ;
#显示内连接
#查询每一个员工的姓名,及关联的部门的名称
Select e.name , d.name from emp e inner join dept d on e.dept_id = d.id;
三、外连接
sql
复制代码
#1.查询emp表的所有数据,和对应的部门信息(左外连接)
Select e.* , d.name from emp e left outer join dept d on d.id = e.dept_id;
#2.查询dept表的所有数据,和对应的员工信息(右外连接)
Select d.* , e.* from emp e right outer join dept d on d.id = e.dept_id;
常用左外连接
四、联合查询
sql
复制代码
Select * from emp where id < 5
union
Select * from emp where age = 10;
五、子查询
1.标量子查询
sql
复制代码
#子查询返回的结果是单个值(数字、字符串、日期等),最简单的形式,这种子查询成为标量子查询。
#1.查询"销售部"的所有员工信息
#a.查询"销售部"部门id
Select id from dept where name = '销售部';
#b.根据销售部id,查询员工信息
Select * from emp where dept_id = 4;
#合并
Select * from emp where dept_id = ( select id from dept where name = '销售部' );
#2.查询在"方东白"入职之后的员工信息
#a.查询方东自的入职日期
Select entrydate from emp where name = '方东自';
#b.查询指定入职日期之后入职的员工信息
Select * from emp where entrydate > '2009-09-12';
#合并
Select * from emp where entrydate > (select entrydate from emp where name = '方东自');
2.列子查询
sql
复制代码
#1.查询销售部和市场部所有员工信息
#a.查询销售部和市场部的部门id
Select id from dept where name = '销售部' or name = '市场部';
#b.根据部门id,查询员工信息
Select * from emp where dept_id in (2,4);
#合并
Select * from emp where dept_id in (select id from dept where name = '销售部' or name = '市场部');
#2.查询比财务部所有人工资都高的员工信息
#a.查询所有财务部人员工资
Select id from dept where name = '财务部';
Select salary from emp where dept_id = 3;
Select salary from emp where dept_id = (select id from dept where name = '财务部');
#b.比财务部所有人工资都高的员工信息
Select * from emp where salary >all (select salary from emp where dept_id = (select id from dept where name = '财务部'));
#3.查询比研发部其中任意一人工资高的员工信息
#a.查询研发部所有人工资
Select salary from emp where dept_id = (select id from dept where name = '研发部');
#b.比研发部其中任意一人工资高的员工信息
Select * from emp where salary > any (select salary from emp where dept id = (select id from dept where name = '研发部'));
3.行子查询
sql
复制代码
#子查询返回的结果是一行(可以是多列),这种子查询称为行子查询
#常用的操作符:=、<>、IN、NOTIN
#1.查询张无忌的薪资及领导相同的员工信息
#a.查询张无忌的薪资及直属领导
Select salary, manager id from emp where name = '张无忌';
#b.查询与张无忌的薪资及直属领导相同的员工信息
Select * from emp where salary = 12500 and managerid = 1;
Select * from emp where (salary, managerid) = (12500,1);
Select * from emp where (salary, managerid) = (select salary,manager id from emp where name = '张无忌');
4.表子查询
sql
复制代码
#子查询返回的结果是一行(可以是多列),这种子查询称为行子查询
#常用的操作符:=、<>、IN、NOTIN
#1.查询张无忌的薪资及领导相同的员工信息
#a.查询张无忌的薪资及直属领导
Select salary, manager id from emp where name = '张无忌';
#b.查询与张无忌的薪资及直属领导相同的员工信息
Select * from emp where salary = 12500 and managerid = 1;
Select * from emp where (salary, managerid) = (12500,1);
Select * from emp where (salary, managerid) = (select salary,manager id from emp where name = '张无忌');