SQL之DQL详解

SQL数据库中的查询语句整理

基础查询

Select * from 数据表; 查看所有数据
Select 字段1,字段2 from 数据表; 查看字段
select 地段名 as 字段别名 from 数据表; 别名查询
select distinct 地段名 from 数据表; 去重查询

运算符筛选

select * from 表名 where 字段名 = '字段值'; 筛选某字段值的行信息
select * from 表名 where 字段名 != '字段值'; 筛选不含某字段值的行信息
select * from 表名 where 字段名 > 字段值; 筛选显示大于字段值的行
select * from 表名 where 字段名 in (a,b); 筛选显示包含a,b值的行
select * from 表名 where 字段名 between 20 and 80; 筛选显示介于20 - 80之间的行
select * from 表名 where 字段名=a and 字段名>b; 交集条件
select * from 表名 where 字段名=a or 字段名>b; 并集条件
select * from 表名 where 字段名 like '_值%'; 近似查询,_占位符,%任意字符
select * from 表名 where 字段名 is null; 空字段查询
select * from 表名 where 字段名 is not null; 非空字段查询

排序

select * from 表名 order by 字段名 asc | desc; 排序
select * from 表名 order by 字段名1 asc,字段名2 desc 多重排序

聚合与分组

select 聚合函数 from 表名 where 字段名xxx;

聚合函数为:count(),max(),min(),sum(),avg()

xxx为筛选条件

相关条件值下的统计值

select

分组字段, 聚合函数(count(*))...

from

数据表名

where

组前筛选

group by

分组字段

having

组后筛选;

分组查询

一般结合聚合函数一起用, 否则: 无意义

where: 组前筛选, 后边不能跟: 聚合函数.

having: 组后筛选, 后边可以跟: 聚合函数.

分页查询

select * from 表名 limit 起始索引, 数据条数;

注:索引从0开始,从0开始则0可以省略不写

经验:总页数:=(总条数 + 每页的数据条数 - 1) // 每页的数据条数

分页查询较为常用,有效减少服务器/用户压力

重分类查询

select case

when 条件1 then 重命名值

when 条件2 then 重命名值2

.....

else 重命名值3

end as 字段名,

from 数据表


SQL之DQL详解
https://linxkon.github.io/SQL之DQL详解.html
作者
linxkon
发布于
2020年3月18日
许可协议