DQL(select)
1、数据查询语言(DQL-Data Query Language):代表关键字:select
13.2.7. SELECT语法_MySQL 中文文档 (mysqlzh.com)

1.1、简单查询:(可以控制结果的字段数量,可以控制列数)
查询多个字段:select 字段名,字段名 from 表名;
查询所有字段:select * from 表名;
用 as 关键字重命名表字段,as 也可以省略:
select empno as ‘员工编号’, ename as ‘员工姓名’, sal*12 as ‘年薪’ from emp; # 列出员工的编号,姓名和年薪
1.2、条件查询:(where关键字,位置是在from关键字之后)


1.3、排序数据(order by)
排序采用 order by 子句,order by 后面 + 排序字段,排序字段可以放多个,多个采用逗号间隔。
order by 默认采用升序asc,如果存在 where 子句那么 order by 必须放到 where 语句的后面 。

order by 默认采用升序asc,如果存在 where 子句那么 order by 必须放到 where 语句的后面 。
如果采用多个字段排序,会先根据第一个字段排序,重复了,再根据第二个字段排序。
单一字段排序
- 按照薪水由小到大排序(默认升序):select * from emp order by sal;
- 取得 job 为 MANAGER 的员工,按照薪水由小到大排序:select * from emp where job='MANAGER' order by sal asc;
- 手动指定按照薪水由大到小排序(手动降序):select * from emp order by sal desc;
多个字段排序
- 首先按照 job 排序,再按照 sal 排序(默认升序):select * from emp order by job,sal;
- 按照 job 和薪水倒序:select * from emp order by job desc, sal desc;
1.4、分组查询(group by 和 having)
注意:若有 group by 语句,那么在 select 语句后面只能跟分组函数+参与分组的字段。
区别:where语句排除的数据是表中的数据,having语句排除的数据是分组后的小组数据。
所以 having 关键字不能单独出现,必须是在分组之后才能使用having语句。
group by 位置是在where关键字之后,order by排序之前。
2、数据处理函数(又称为单行处理函数,特点:输入一行输出一行)


3、分组函数(又称为聚合函数、多行处理函数)
注意:分组函数自动忽略空值,不需要手动的加 where 条件排除空值。
select count(*) from emp where 条件; # 符合条件的所有记录总数。
select count(comm) from emp; # comm 这个字段中不为空的元素总数。
注意:分组函数不能直接使用在 where 关键字后面。
mysql> select ename,sal from emp where sal > avg(sal); # 报错
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)