MySQL
查询条件之having
# having的功能与where一样
where 在分组之前用, where中写的条件必须在表中存在
having 在分组之后用
# 查询每个部门中大于30岁的平均工资,并且,保留中平均工资在10000以上的
select post, avg(salary) as avg_salary from emp where age > 30 group by post having avg(salary) > 10000;
查询条件之distinct
# 去重的前提条件:数据必须一毛一样
# 有主键存在,没必要去重
# 去重年龄
select dictinct age from emp;
查询条件之order by
select * from emp order by salary;  # 默认是升序排列
select * from emp order by salary asc; # 升序,可以不指定,建议指定
select * from emp order by salary desc;
# 排序还可以指定多个字段进行排序
 select *from emp order by age, salary desc ;
# 查询每个部门中大于30岁的平均工资,并且,保留中平均工资在10000以上的, 按照平均工资降序排列
select post, avg(salary) as avg_salary from emp where age > 30 group by post having avg(salary) > 10000 order by avg(salary) desc;
查询条件之limit
分页,限制数据
select *from emp limit 5;  # 限制前5条数据
select *from emp limit 5, 5;  # 从第5条开始,查询5条数据
# 查询工资最高的员工
select max(salary) from emp;
select * from emp order by salary desc, age asc limit 1;
多表查询
1. 子查询,  一个SQL语句的结果作为另外一个SQL的条件
# 查询egon所在的部门
1) 查询egon所在部门的id
select dep_id from emp where name='egon';
2) 在拿着dep_id取dep表中查询部门名称
	select * from dep where id = (select dep_id from emp where name='egon');
	
2. 连表查询, 将多个表拼接成一张表,当成单表查询
select *from emp,dep;
select * from emp,dep where emp.dep_id=dep.id;
# inner join  内连接
select * from emp inner join dep on emp.dep_id=dep.id;
# left join   左连接 以左表为基表,查询出左表的所有数据,右表的数据用null填充
select * from emp left join dep on emp.dep_id=dep.id;
# right join  右连接 以右表为基表,查询出右表的所有数据,左表的数据用null填充
select * from emp right join dep on emp.dep_id=dep.id;
# union  全连接
select * from emp left join dep on emp.dep_id=dep.id
union
select * from emp right join dep on emp.dep_id=dep.id;
数据库练习题大礼包(能做几道是几道 内附答案)
	https://www.cnblogs.com/Dominic-Ji/p/10875493.html