字符串函数
练习:
# 查询并拼接 user 表中的 name 和 email 字段
select concat(name, email) from user;
# 查询 user 表中的 email,要求结果字母都转化为大写
select upper(email) from user;
# 查询 user 表中的 id,要求结果为8位,前面不足补零
select lpad(id, 8, '0') from user;
# 查询 user 表中的 id,要求结果为8位,后面不足补'-'
select rpad(id, 8, '-') from user;
# 查询 user 表中的 name,要求去掉前后空格
select trim(name) from user;
# 查询 user 表中的 email,只要前面长度为 8 的部分
select substring(email, 1, 8) from user;
数值函数
练习:
# 查询 book 表中 price,向上取整
select ceil(price) from book;
# 查询 book 表中 price,向下取整
select floor(price) from book;
# 查询 book 表中 price 并除以 2 取模
select mod(price, 2) from book;
# 生成 0 ~ 1 的随机数
select rand();
# 查询 book 表中 price,四舍五入,保留一位小数
select round(price, 1) from book;
# 生成一个六位数的验证码
select lpad(round(rand() * 1000000, 0), 6, '0');
日期函数
练习:
# 当前日期
select curdate();
# 当前时间
select curtime();
# 当前日期和时间
select now();
# 获取年月日
select year(now());
select month(now());
select day(now());
# 当前时间延后 50年
select date_add(now(), interval 50 year);
# 返回两段时间的天数
select datediff(curdate(), '2001-3-1');
# 查询所有订单的下单天数,并按下单天数降序排序
select order_id, datediff(curdate(), order_time) as o from `order` order by o desc;
流程控制函数
练习:
# if 语句
select if(true, 'true', 'false');
# if null 语句
select ifnull('true', 'false');
select ifnull('', 'false'); # ''不算空值
select ifnull(null, 'false');
# 查询 user 表中的用户姓名和地址(北上广 -> 一线城市,其他 -> 二线城市)
select user_name,
case substring(address, 1, 2)
when '北京' then '一线城市'
when '上海' then '一线城市'
when '广东' then '一线城市'
else '二线城市'
end
from user;
# 统计班级每个学生每科的成绩,85及以上优秀,60及以上及格,60以下不及格
select id, name,
(case when math >= 85 then '优秀' when math >= 60 then '及格' else '不及格' end) as math,
(case when english >= 85 then '优秀' when english >= 60 then '及格' else '不及格' end) as english,
(case when chinese >= 85 then '优秀' when chinese >= 60 then '及格' else '不及格' end) as chinese
from score;
以上整理自:黑马程序员 MySQL数据库入门到精通,从mysql安装到mysql高级、mysql优化全囊括_哔哩哔哩_bilibili