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 语句的后面 。
如果采用多个字段排序,会先根据第一个字段排序,重复了,再根据第二个字段排序。
  单一字段排序
  • 按照薪水由小到大排序(默认升序):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);  # 报错

posted @ 2022-07-25 10:00  鹿先森JIAN  阅读(239)  评论(0编辑  收藏  举报