1.查看字符集、获取字符床字节长度
#查看字符集
show variables like '%char%' ,查看当前客户端(Client)是什么编码。
获取字节数组用函数length()
select length('hahaha哈哈哈')
#如果字符集是utf8,一个汉字占三个字节,结果为15;
#如果是gbk每个汉字占两个字节,结果为12;
2.数学函数
2.1 ceil 向上取整,返回大于等于该参数的最小整数;
select ceil(1.12)#结果为2
2.2 floor 向下取整,返回小于该参数的最大整数
select floor(-9.12),结果为-10
2.3 round 四舍五入,该函数有四种输入参数类型
select round(1.45)#完全四舍五入,结果为1
select round(-1.65)#完全四舍五入,结果为-2
select round(1.4567,2),#小数点后保留两位,结果为1.46
2.4 truncate 截取数值,截取输入参数的第几位小数,意思就是后面不管是什么都舍弃
select truncate(1.5999999,2)#结果为1.59
2.5 mod 取余数
select mod(-10,-3)#结果为-1
select mod(10,3)#结果为1,等价于select 10%3;
3.日期函数
3.1 now
select mow()#获取当前时间,年月日时分秒eg:2021-5-2 22:57:02
4.其他
4.1.在一个表中按照多个字段进行分组,然后把需要的列进行累加秀求和
例如demo表结构如下:
create table demo
(
id bigint unsigned auto_increment comment '记录ID'primary key,
a_id bigint unsigned not null comment '字段a',
b_id bigint unsigned not null comment '字段b',
c_id bigint unsigned default 0 not null comment '字段c',
d_id bigint unsigned default 0 not null comment '字段d',
usertime int unsigned default 0 not null comment '时长,单位秒',
created_at timestamp default CURRENT_TIMESTAMP not null comment '创建时间',
)
comment 'demo表哈哈哈' charset = utf8mb4;
现在要按照a_id和b_id进行分组,并且也把created_at进行分组,精确到天,然后把usertime 进行累加,然后按照a_id进行排序,查询出前500条内容,sql如下:
select a_id,b_id,sum(usertime) as total_usertime, created_at from
(select a_id,b_id,usertime,created_at from demo ) as temp
where 1=1
group by app_id,mode,left(created_at,10)#把左边十位进行分组
order by a_id
limit 500;
4.2. 创建一个索引:
create index 索引名字
on 表名 (字段名);