SQL(三)

第四节.SQL(三)

DQL-数据查询语言 select
DQL语法
  1. 基本查询
  • select 字段列表
  • from 表名列表
  1. 条件查询
  • where 条件列表
  1. 聚合函数
  2. 分组查询
  • group by 分组字段列表
  • having 分组后条件列表
  1. 排序查询
  • order by 排序字段列表
  1. 分页查询
  • limit 分页参数
--------------------------------------------------------------------------------------------------
DQL-基本查询
  1. 查询多个字段
select 字段1,字段2... from 表名;
select *from 表名;
  1. 设置别名
select 字段1 [as 别名1],字段2 [as 别名2] ... from 表名;

as 可以省略 3. 去除重复记录

select distinct 字段列表 from 表名;
DQL-条件查询
  1. 语法
select 字段列表 from 表名 where 条件列表;
  1. 条件
比较运算符 功能
> 大于
>= 大于等于
< 小于
<= 小于等于
= 等于
!= 或 <> 不等于
BETWEEN ... AND ... 在某个范围之内(含最小、最大值)
IN(...) 在 in 之后的列表中的值,多选一
LIKE 模糊匹配(_匹配单个字符,%匹配任意个字符)
IS NULL 是 NULL
逻辑运算符 功能
AND 或 && 并且(多个条件同时成立)
OR 或 || 或者(多个条件任意一个成立)
NOT 或 ! 非,不是

For example

select * from emp where name like '__';
#查询名字为两个字的员工信息
select * from emp where idcard like '%x';
#查询身份证带x的员工信息
DQL-聚合函数
  1. 介绍 将一列数据作为一个整体,进行纵向计算
  2. 常见聚合函数
函数 功能
count 统计数量
max 最大值
min 最小值
avg 平均值
sum 求和
  1. 语法
select 聚合函数(字段列表) from 表名;

null值不参与聚合函数计算

DQL-分组查询
  1. 语法
select 字段列表 from 表名 [where 条件] group by 分组字段名 [having 分组后过滤条件];

For example

select address,count(*) as address_count from emp where age > 45 group by address having address_count >= 3;
#查询年纪大于45岁,根据地址分组,查询员工数量大于等于3的地址
  1. where 与 having区别
  • 执行时间不同:where在分组之前进行过滤,不满足where条件的不参与分组;having是分组之后对结果进行过滤
  • 判断条件不同:where不能对聚合函数进行判断,而having可以 注意
  • 执行顺序 where>聚合函数>having
  • 分组之后,查询的字段一般是聚合函数或者分组字段,查询其他字段无意义
DQL-排序查询
  1. 语法
select 字段列表 from 表名 order by 字段1 排序方式1,字段2 排序方式2;
  1. 排序方式
  • ASC: 升序(默认)
  • DESC: 降序
  • 多字段排序时,只有第一个字段值相同时才会根据第二个字段进行排序

For example

select * from emp order by age asc;
select * from emp order by age;
#以上排序结果相同,asc为默认排序
select * from emp order by age asc,entrydate desc;
#先根据年龄升序排序,再进行入职时间降序排序
DQL-分页查询
  1. 语法
select 字段列表 from 表名 limit 起始索引,查询记录数;

注意

  • 起始索引从0开始,起始索引=(查询页码-1)*每页记录数
  • 分页查询是数据库的方言,不同数据库有不同的实现,MySQL是LIMIT
  • 如果查询的是第一页数据,起始索引可以省略,直接简写为LIMIT 10

For example

select * from emp limit 0,10;
select * from emp limit 10;
#结果相同
select * from emp limit 10,10;
#查询第2页员工信息,每页记录10条
案例练习
  1. 查询年龄为20,21,22,23岁的女员工信息
select * from emp where gender = '女' && age in (20,21,22,23);
  1. 查询性别为男,并且年龄在20-40岁(含)以内的姓名为三个字的员工
select * from emp where gender = '男' && age between 20 and 40 && name like '___';
  1. 统计员工表中,年龄小于60岁的,男性员工和女性员工的人数
select genderm,count(*) from emp where age < 60  group by gender;
  1. 查询所有年龄小于等于35岁员工的姓名和年龄,并对查询结果按年龄升序排序,如果年龄相同投入职时间降序排序
select name , age from emp where age <= 35 order by age asc,entrydate desc;
  1. 查询性别为男,且年龄在20-40岁(含)以内的前5个员工信息,对查询的结果按年龄升序排序,年龄相同投入职时间升序排序
select * from emp where gender = '男' && age between 20 and 40 order by age asc,entrydate desc limit 0,5;
DQL-执行顺序
  • 编写顺序:select -> from -> where -> group by -> having -> order by -> limit
  • 执行顺序: from -> where -> group by -> having -> select -> order by -> limit

本文章使用limfx的vscode插件快速发布