SQL查询语句语法结构和运行顺序:
语法结构:selcet–from–where–group by–having–order by–limit
运行顺序:from–where–group by–having–order by–select
- select&from
标准语法:
select 字段名
from 表名
- where
标准语法:
select 字段名
from 表名
[where 表达式]
运算符查询语法:
select 字段名
from 表名
where 字段名 运算符 值
模糊查询语法:
select 字段名
from 表名
where 字段名 like '通配符+字符'
使用多条件查询:
select 字段名
from 表名
where 条件代码1 and|or 条件代码2
- order by
标准语法:
select 字段名
from 表名
[order by 字段名 asc|desc]
asc表示升序,从小到大排序
desc表示降序,从大到小排序
不写默认为升序排序
- limit
标准语法:
select 字段名
from 表名
[where 表达式]
[order by 字段名 asc|desc]
[limit [位置偏移量,]行数]
limit[位置偏移量,]行数 限制查询结果集显示的行数
limit子句是可选项,行数是子句中的必选参数,参数位置偏移量是可选参数
查询结果返回前n行:
select 字段名
from 表名
[where 表达式]
[order by 字段名 asc|desc]
[limit n]
查询结果返回第x+1行开始的n行到x+n行:
select 字段名
from 表名
[where 表达式]
[order by 字段名 asc|desc]
[limit x,n]
- 聚合函数&group by
聚合函数包括:
avg()
count()
max()
min()
sum()
标准语法:
select 字段名1
from 表名
[where 表达式]
[group by 字段名1]
[order by 字段名 asc|desc]
[limit [位置偏移量,]行数]
group by 字段名 规定依据哪个字段分组聚合
group by核心句子是可选项,使用该句是为了依据相同字段值分组后进行聚合运算,常和聚合函数联用
- having
标准语法:
select 字段名
from 表名
[where 表达式]
[group by 字段名]
[having 表达式]
[order by 字段名 asc|desc]
[limit [位置偏移量,]行数]
having 表达式 限定分组聚合后的查询行必须满足的条件
having核心句子是可选项,使用该剧自是为了对group by分组后的数据进行筛选
- 部分常见函数
- 数学函数
round(x,y)---四舍五入函数
- 字符串函数
concat(s1,s2,...)---连续字符串函数
replace(s,s1,s2)---替换函数
left(s,n)、right(s,n)&substring(s,n,len)---截取字符串一部分的函数
left函数返回字符串s最左边n个字符
right函数返回字符串s最右边n个字符
substring函数返回字符串s从n个字符起取长度为len的子字符串,n也可以为负值,则从倒数第n个字符起取长度为len的子字符串,没有len值则取从第n个字符串起到最后一位
- 数据类型转换函数
cast(x as type)---转换数据类型的函数
- 日期时间函数
year(date)、month(date)&day(date)---获取年月日的函数
date_add(date,interval expr type)&data_sub(date,interval expr type)---对指定起始时间进行加减操作
datediff(date1,date2)---计算两个日期之间间隔的天数
date_format(date,format)---将日期的时间格式化
- 条件判断函数—满足不同条件,执行相应流程
if(expr,v1,v2)
case when
case expr when v1 then r1 [when v2 then r2]...[else rn] end
1157

被折叠的 条评论
为什么被折叠?



