一、其它查询关键字

1.1 having 过滤

功能上having与where是一模一样的
但是使用位置上有所不同
	where在分组之前使用
    having在分组之后使用
    
    
1.统计各部门年龄在30岁以上的员工平均工资,并且保留平均工资大于10000的部门
# 1.先筛选出所有30岁以上的员工
	select * from emp where age>30;
# 2.然后再按照部门分组
	'''SQL语句的查询结构我们也可以直接看成是一张表'''
	select post,avg(salary) from emp where age>30 group by post;
# 3.分组之后做过滤操作
	select post,avg(salary) from emp 
    	where age>30 
        group by post 
        having avg(salary)>10000
        ;

1.2 distinct 去重

去重有一个非常严格的前提条件 数据必须是完全一样
'''如果数据带有主键那么肯定无法去重'''
select distinct age from emp;

1.3 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 desc,salary asc;

# 统计各部门年龄在10岁以上的员工平均工资,并且保留平均工资大于1000的部门,然后对平均工资进行排序
	select post,avg(salary) from emp 
    	where age>10
        group by post
        having avg(salary)>1000
        order by avg(salary);

1.4 limit 分页

用来限制数据的展示条数
select * from emp limit 5;  # 前五条
select * from emp limit 5,5;  # 起始位置、条数

# 查询工资最高的人的详细信息
	# 先按照工资排序 然后限制展示条数
select * from emp order by salary desc limit 1;

1.5 regexp 正则

正则表达式
	用一些特殊符号的组合去字符串中筛选出符合条件的数据
select * from emp where name regexp '^j.*(n|y)$';
# '^j.*(n|y)$'  j开头 中间无所谓 n或者y结尾

二、多表查询

2.1 思想

1.子查询
	分步解决问题
    将一条SQL语句的查询结果用括号括起来当作另外一条SQL语句的查询条件
 
2.连表操作
	先将所有需要用到的表拼接到一起(一张表)
    然后就是转换成单表查询

2.2 子查询

# 查询jason所在的部门名称
	# 第一步 先获取jason所在的部门id
    select dep_id from emp where name='jason';
   	# 第二步 根据id号去部门表中筛选
    select * from dep where id = 200;
    # 完整句式
    select * from dep where id=(select dep_id from emp where name='jason');

2.3 连表操作

# 前戏(了解)
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;
posted on 2021-04-29 19:07  lzl_121  阅读(36)  评论(0编辑  收藏  举报