select 列名 from 表名,实际应用中很少使用*号
select distinct 列名 from 表名,查找列并去重(只能查询到去重的属性列,无法查询其他字段)
select 列名 from 表名 group by 列名,查找列并去重(可根据需求查询对应的其他字段推荐使用)
select distinct 列名 from 表名 where 条件(布尔表达式) group by 列名 having 组条件 order by 列名 asc(升序)/desc(降序) limit 参数
(order by 默认升序)
使用limit限制结果集,
只给定一个参数,表示返回最大的记录行数目
给定两个参数,第一个参数指定第一个返回记录行的偏移量,第二个参数指定返回记录行的最大数目
检索从某一偏移量到记录集的结束所有的记录行,可指定第二个参数为-1,初始记录行的偏移量是0
select from table limit 5,5;检索6-10行
(等同于select from table limit 5 offset 5;跳过5条数据行)
select from table limit 10,-1;检索11-最后
select from table limit 5;检索前5行
查询后的列重命名
select 列名 as 新列名 from 表名,as可以省略,新列名加引号即为引号内的内容,不加引号若为小写会解析为大写
查找指定范围
select 列名 from 表名 where 列名 between 下限 and 上限
(等同于select 列名 from 表名 where 列名 > 下限 and 列名 < 上限)
select 列名 from 表名 where 列名 not between 下限 and 上限
(等同于select 列名 from 表名 where 列名 < 下限 and 列名 > 上限)
select 列名 from 表名 where 列名 in (“A”,”B”,”C”)
即select 列名 from 表名 where 列名 = “A” or 列名 = “B” or 列名 = “C”
select 列名 from 表名 where 列名 not in (“A”,”B”,”C”)
即select 列名 from 表名 where 列名 != “A” and 列名 != “B” and 列名 != “C”
过滤空值
select 列名 from 表名 where 列名 is (not) NULL(运行效率高)
select 列名 from 表名 where 列名 !=””(运行效率低)
字符匹配
:匹配任意一个字符
%:匹配0个或多个字符
[]:匹配[]中的任意一个字符
[^]:不匹配[]中的任意一个字符
(1)查找”A”开头的
select 列名 from 表名 where 列名 like “A%”
(2)查找”A”开头的三个字母的
select 列名 from 表名 where 列名 like “A“
rtrim()可以去掉右空格
select 列名 from 表名 where rtrim(列名) like “A“
(3)查找”A”,”B”,”C”开头的
select 列名 from 表名 where 列名 like “[ABC]%”
(4)查找第二个字母为”A”或”B”的
select 列名 from 表名 where 列名 like “[AB]%”
(5)查找最后一个字母不是”A”,”B”,”C”的
select 列名 from 表名 where 列名 like “%[^ABC]”
SQL提供的统计函数
count(*):统计表中元组个数,除此之外其他的函数计算过程中均忽略NULL值
count(列名):统计本列列值个数
sum(列名):计算列值总和
avg(列名):计算列值平均值
max(列名):求列值最大值
min(列名):求列值最小值
round(列名,保留位数):四舍五入函数
查找最大/小值
select max(列名) as 列名 from 表名 where 条件
select 列名 from 表名 where 条件 order by 列名 desc/asc limit 1
having
having子句用于对分组后的结果再进行过滤,它的功能有点像where子句,但它用于组而不是单个记录。
在having子句中可以使用统计函数,但在where子句中不能。
having通常与group by子句一起使用。
