### day2
-- where语句
where dept_id =2 and sal > 1000;
select * from emp
where job in('人事','程序员');
select * from emp
where job not in('人事');
select * from emp
where sal between 2000 and 3000;
-- distinct 多少个种类(去重) 该关键字要紧跟在select后使用
select distinct job from emp
-- like模糊查询
-- _任意一个字符 %任意多个字符
select * from emp
where name like '%备%';
where name like '张%';
select * from emp
where name like '_骨%';
select name,job from emp
where job like '_售%';
-- is not null 判断是否为null
select * from emp
where manager is not null;
-- order by 默认从小到大进行排序 该语句只能放在查询语句的最后一句
-- asc 从小到大
-- desc 从大到小
select * from emp
order by sal;
order by sal asc; -- 一样
select * from emp
order by sal desc;
-- 分页查询
-- limit 每页显示的个数*(第几页-1),每页显示的个数
select * from emp
limit 6,3;
-- 在查询字段时可以使用表达式
select sal,sal*12 from emp
-- 别名
select name 名字 ,sal 月薪,sal*12 年薪 from emp
-- 聚合函数
select min(sal) 员工最少工资 from emp
-- group by 分组
select dept_id,avg(sal) 平均工资 from emp
group by dept_id;
#查询平均工资最高的部门id和平均工资
select dept_id,avg(sal) 平均工资 from emp
group by dept_id
order by avg(sal) desc
limit 0,1;
#查询部门平均工资高于2000的那些部门的平均工资具体是多少
select dept_id ,avg(sal) 平均工资 from emp
group by dept_id
-- having 子句跟在group by后,对分组统计的结果再进行筛选
having avg(sal)>=2000; -- 聚合函数要在having后使用
select dept_id ,avg(sal) from emp
group by dept_id
having avg(sal)>1000;
select dept_id,sum(sal) 工资总和 from emp
where manager is not null
group by dept_id
having sum(sal)>5400;
-- 子查询
select * from emp
where sal>(select avg(sal) 平均工资 from emp);
#比沙僧平均工资低的员工信息
select * from emp
where sal<(select sal from emp
where name='沙僧');
# 子查询分类(按照查询结果集分类):
-- 单行单列子查询 【结果集只有一个值】
-- 通常用于过滤条件中使用!
-- 可以配合 > < >= <= != <>
-- 多行单列子查询 【结果集有多个值】
-- 可以配合 in、 all 、 ang
-- > all(子查询): 大于子查询结果中最大的
-- < all(子查询): 小于查询结果中最小的
-- > any(子查询): 大于查询结果中最小的
-- < ang(子查询): 小于查询解过中最大的
-- in(子查询): 等于子查询结果集中的任意一个
-- 多行多列子查询 【结果集是一张表】
-- 通常就当做一张表使用,可以跟在frokm子句之后, 或者跟在DDL语句中基于一个结果集创建表
-- 将1号部门员工信息单独定义一张表名为emp_dept11
create table emp_dept1 as
select * from emp
where dept_id=1;
select * from emp_dept1;
-- 两表联查
select * from dept,emp
where emp.dept_id = dept.did;
-- 当两张表的字段重名时,用”表.“来区别
-- 可以给表也起别名 ....from dept d emp e 如果更改别名,下面代码要把表的名字都用别名
select emp.id 用户,dept.dname 部门名称 from dept,emp
where emp.dept_id =dept.did;
mysql学习笔记第二天
最新推荐文章于 2024-10-02 06:14:43 发布
本文介绍了SQL中的基本查询语句,包括WHERE子句用于条件筛选,DISTINCT去除重复项,LIKE进行模糊匹配,ORDERBY用于排序,LIMIT实现分页,以及GROUPBY和HAVING对数据进行分组和过滤。此外,还讨论了子查询和表联查的应用。
摘要由CSDN通过智能技术生成