# 1. 查出至少有一个员工的部门,显示部门编号、部门名称、部门位置、部门人数。
分析:(分析要查的表): (显示的列):(关联条件):(过滤条件):[分组条件]:[排序条件]:[分页条件]:SELECT d.deptno, dname, loc,count(empno)FROM dept d JOIN emp e
ON d.deptno = e.deptno
GROUPBY d.deptno;
自连接查询
createtable area(pid intprimarykeyauto_increment,name varchar(20),city_id int);insertinto area values(1,'广东省',null),(2,'江西省',null),(3,'广州市',1),(4,'深圳',1),(5,'东莞',1),(6,'南昌',2),(7,'赣州',2),(8,'九江',2);# 例如,使用自连接查询命令完成:# (1)把区域表tb_area分别理解成两个表:省表province、城市表city;# (2)自连接查询省份编号、省名、城市名、城市编号的展示结果;select province.pid,province.name,city.name,city.pid from area province join area city on province.pid = city.city_id;# (3)自连接查询省的名称为广东省的所有城市信息。select a.pid,a.name,b.name,b.pid from area a join area b on a.pid = b.city_id where a.name ='广东省';
-- todo 子查询三种情况--------------------# 1.子查询当条件(单值对比--where 后边)-- 查询 工资高于平均工资的员工信息select*from emp where sal >(selectavg(sal)from emp);# 2.子查询当条件(多值对比)-- 查询销售部和财务部所有员工信息.select*from emp where deptno in(select deptno from dept where dname ='销售部'or dname='财务部');select*from emp where deptno in(select deptno from dept where dname in('销售部','财务部'));select e.*from emp e join dept d on e.deptno = d.deptno where dname ='销售部'or dname='财务部';-- 连接查询实现# 3.子查询当临时表(出现在from的后边位置)-- 查询工资高于15000元的员工信息和他的部门信息select*from emp where sal >15000;select d.dname,d.loc,e.*from dept d join(select*from emp where sal >15000) e on d.deptno = e.deptno;
union连接查询
union: 纵向拼接去重
union all:纵向拼接不去重
-- 需求:查询工资大于28000或者部门是10号部门的员工信息.select*from emp where sal >28000unionselect*from emp where deptno =10;select*from emp where sal >28000unionallselect*from emp where deptno =10;-- 两个表列和类型相同但是名字不同也可以拼接.createtable teacher(t_id int,t_name varchar(20),t_gender varchar(20));createtable student(s_id int,s_name varchar(20),s_gender varchar(20));insertinto teacher values(1,'张三','男'),(2,'李四','男'),(3,'王五','男'),(4,'小美','女');insertinto student values(1,'tom','男'),(2,'jerry','男'),(3,'jack','男'),(4,'rose','女');-- 需求 查询男性的学生和老师.select t_id id,t_name name,t_gender gender from teacher where t_gender ='男'unionselect*from student where s_gender ='男';