本文共 2568 字,大约阅读时间需要 8 分钟。
获取字符串的字节数
select length('abcd'); -- 返回值:4select length('数据库abc'); -- 返回值:与字符编码类型有关
连接多个字符串
select concat('abc', 'def'); -- 返回值: 'abcdef'
将字符串转换为大写或小写
select upper('HelloWorld'); -- 返回值: HELLOWORLDselect lower('HELLOWORLD'); -- 返回值: helloworld
字符串截取
-- 从第4个字符开始到最后select substr('目标字符串',4); -- 注意:MySQL索引从1开始-- 从第二个字符开始截取1个字符select substr('目标字符串',2,1);
查找子字符串在源字符串中的起始位置
select instr('目标字符串','子字符串'); -- 返回结果为子字符串起始位置,找不到则返回0
去掉字符串前后空格
select trim(' aaaa '); -- 返回值: 'aaaa'
替换字符串中的子串
select replace('目标字符串','字符','zifu');
四舍五入
select round(1.45); -- 返回值: 1select round(1.567,2); -- 返回值:1.57
向上取整和向下取整
select ceil(-1.3); -- 返回值: -1select floor(1.65); -- 返回值:1
截断小数点
select truncate(1.65,1); -- 返回值:1.6
select now(); -- 返回当前日期时间select curdate(); -- 返回当前系统日期select curtime(); -- 返回当前系统时间select unix_timestamp(now()); -- 返回日期时间转时间戳
select YEAR(NOW()); -- 返回年份select month(now()); -- 返回月份(1到12)select day(now()); -- 返回日期(几号)select hour(now()); -- 返回小时select minute(now()); -- 返回分钟select second(now()); -- 返回秒数select monthname(now()); -- 返回月份名称select weekday(now()); -- 返回星期几(0为星期一)select weekofyear(now()); -- 返回本年的第几个星期
select str_to_date('2018-1-12','%y-%m-%d');
select date_format(now(),'%Y-%m-%d %H:%i:%s');
select if('10>1','大','小');
--案例:员工表中,部门号是30,显示工资为1.1倍;部门号是40,显示工资为1.2倍;其他显示原工资select salary as 原工资, department_id, case department_idwhen 30 then salary*1.1when 50 then salary*1.2else salaryend as 新工资from employees;
select salary, casewhen salary>20000 then 'A级工资'when salary>10000 then 'B级工资'else 'C级工资'end as 工资等级from employees;
select ifnull(expr1, expr2); -- 如果expr1不为NULL,返回expr1,否则返回expr2
alter table t_student auto_increment = 114;
select distinct name from t_student order by convert(name using gbk);
select * from (select * from t_student order by rand()) agroup by a.name;
-- 获取今天的数据select * from 表名 where to_days(create_time) = to_days(now());-- 获取本周的数据select * from 表名 where yearweek(date_format(submittime, '%Y-%m-%d')) = yearweek(now());-- 获取本月的数据select * from 表名 where date_format(pudate, '%Y%m') = date_format(curdate(), '%Y%m');
select sum(integral) from t_userwhere enabled = 1and to_days(create_time) = to_days(now())and id = 1;
转载地址:http://audfk.baihongyu.com/