MySQL 学习笔记(四) 常用基本函数
程序员文章站
2022-05-30 12:13:02
...
文章目录
MySQL 常用基本函数
Numeric Functions 数字函数
SELECT ROUND(5.746, 2); -- => 5.75 @四舍五入,后面是保留几位
SELECT TRUNCATE(5.8964, 2); -- => 5.89 @直接保留几位,不四舍五入
SELECT CEILING(5.2); -- => 6 @取大于该数的最小整数
SELECT FLOOR(5.2); -- => 5 @取小于该数的最大整数
SELECT ABS(-6.4); -- => 6.4 @取绝对值
SELECT RAND(); -- => 0.18525891582040016 @取随机值
String Functions 字符串函数
SELECT UPPER('Sky'); -- => SKY @大写
SELECT LOWER('Sky'); -- => sky @小写
SELECT LTRIM(' Sky'); -- => Sky @去除左半边的空格
SELECT RTRIM('Sky '); -- => Sky @去除右半边的空格
SELECT TRIM(' Sky '); -- => Sky @去除所有空格
SELECT LEFT('Kindergarten',4); -- => Kind @选择左边从1开始的4个字符
SELECT RIGHT('Kindergarten', 6); -- => garten @选择从右边开始的6个字符
SELECT SUBSTRING('Kindergarten', 3,5); -- => nderg @截取从第三个位置开始的长度为5的字串
SELECT SUBSTRING('Kindergarten', 3 ); -- => ndergarten @截取从3开始到结束的所有字符
SELECT LOCATE('n','Kindergarten'); -- => 3 @返回第一个n所在的位置
SELECT REPLACE('Kindergarten','en','dn'); -- => Kindergarden @找到en,把en替换成dn
SELECT CONCAT('first','last'); -- => firstlase @合并
Date Functions 日期函数
Basic Functions 基本日期函数
SELECT NOW(), CURDATE(), CURTIME(); -- => 2021-02-06 15:43:56, 2021-02-06, 15:43:56 @现在时间,当下日期,当下时间
SELECT YEAR(NOW()); -- => 2021 @返回当下年份
SELECT SECOND(NOW()); -- => 56 @返回当下时间(秒)
SELECT DAYNAME(NOW()); -- => Saturday @返回今天星期几
SELECT MONTHNAME(NOW()); -- => February @返回当下月份
SELECT EXTRACT(DAY FROM NOW()); -- => 6 @返回日期
SELECT EXTRACT(YEAR FROM NOW()); -- => 2021 @返回年份
Formatting Dates and Times 日期和时间格式化函数
SELECT DATE_FORMAT(NOW(),'%y'); -- => 21 @格式化年份(只返回两位数)
SELECT DATE_FORMAT(NOW(),'%Y'); -- => 2021 @格式化年份(返回四位数)
SELECT DATE_FORMAT(NOW(),'%m'); -- => 2 @格式化月份(数字表示)
SELECT DATE_FORMAT(NOW(),'%M'); -- => February @格式化月份(名字形式)
SELECT DATE_FORMAT(NOW(),'%d'); -- => 6 @格式化日期
SELECT DATE_FORMAT(NOW(),'%D'); -- => 6th @格式化日期(带有序号)
Caculating Dates and Times 计算日期和时间函数
SELECT DATE_ADD(NOW(),INTERVAL 1 YEAR ); -- => 2022-02-06 15:49:52 @年份加1
SELECT DATE_ADD(NOW(),INTERVAL -1 YEAR ); -- => @年份加-1
SELECT DATE_SUB(NOW(),INTERVAL 1 YEAR ); -- => @份减1
SELECT DATE_SUB(NOW(),INTERVAL -1 YEAR ); -- => @年份减去-1
SELECT DATEDIFF('2021-02-05 09:00','2021-02-01 17:00:00'); -- => 4 @计算日期差(不关心具体时间差)
SELECT TIME_TO_SEC('09:00') - TIME_TO_SEC('09:02') -- => -120 @计算时间差(具体到秒)
IF Function
SELECT
order_id,
order_date,
IF (
YEAR(order_date) = 2019,
'ACTIVE',
'ARCHIVED'
)
FROM orders;
IFNULL and COALESCE Function
IFNULL
SELECT
order_id,
IFNULL(shipper_id,'Not assigned') AS shipper
FROM orders;
COALESCE
SELECT
order_id,
COALESCE(shipper_id,comments,'Not assigned') AS shipper
FROM orders;
CASE Operator
SELECT
order_id,
CASE
WHEN YEAR(order_date) = YEAR(NOW()) THEN 'Active'
WHEN YEAR(order_date) = YEAR(NOW()) - 1 THEN 'Last Year'
WHEN YEAR(order_date) < YEAR(NOW()) - 1 THEN 'Archived'
ELSE 'Future'
END AS category
FROM orders;