使用的是MySQL数据库
1. 数值函数
- 搜索数值函数的完整名单 mysql numeric functions
SELECT
ROUND(5.76),
ROUND(5.7435, 2),
TRUNCATE(5.74635, 2),
CEILING(5.2),
FLOOR(5.8),
ABS(-5.2),
RAND();
2. 字符串函数
- 搜索字符串函数的完整名单 mysql string functions
SELECT
LENGTH('sky'),
UPPER('sky'),
LOWER('Sky'),
LTRIM(' PINK'),
RTRIM('RED '),
TRIM(' blue '),
LEFT('Kindergarten', 4),
RIGHT('Kindergarten',4),
SUBSTRING('Kindergarten',4,5),
SUBSTRING('Kindergarten',3),
LOCATE('n','Kindergarten'),
LOCATE('q','Kindergarten'),
REPLACE('Kindergarten','garten','garden'),
CONCAT('first','last');
3. 日期函数 处理日期和时间
SELECT
NOW(),
CURDATE(),
CURTIME();
SELECT
YEAR(NOW()),
YEAR('2021-12-02'),
MONTH(NOW()),
DAY(NOW()),
HOUR(NOW()),
HOUR('01:02:03'),
MINUTE(NOW()),
SECOND(NOW());
SELECT
DAYNAME(NOW()),
DAYNAME('2021-12-02'),
MONTHNAME(NOW());
SELECT
EXTRACT(YEAR FROM NOW()),
EXTRACT(MONTH FROM '2021-12-02');
SELECT *
FROM orders
WHERE YEAR(order_date) = YEAR(NOW());
4. 格式化日期和时间
- 格式化日期和时间格式的完整名单:mysql date format string
SELECT
DATE_FORMAT(NOW(), '%y'),
DATE_FORMAT('2021-12-02','%y'),
DATE_FORMAT(NOW(), '%Y'),
DATE_FORMAT(NOW(), '%m'),
DATE_FORMAT(NOW(), '%M'),
DATE_FORMAT(NOW(), '%d'),
DATE_FORMAT(NOW(), '%D'),
DATE_FORMAT(NOW(), '%Y %m %d');
SELECT
TIME_FORMAT(NOW(), '%H:%i %p');
5. 计算日期和时间
- (1) 在日期基础上增加一天或一小时;(2) 计算两个日期的间隔。
SELECT
DATE_ADD(NOW(), INTERVAL 1 DAY),
DATE_ADD('2021-12-04 01:02:03', INTERVAL -1 DAY);
SELECT
DATE_SUB('2021-12-03', INTERVAL 1 DAY);
SELECT
DATEDIFF('2021-12-03','2021-11-29'),
DATEDIFF('2021-11-29','2021-12-03'),
DATEDIFF('2021-12-03 09:00','2021-11-29 05:00');
SELECT
TIME_TO_SEC(NOW()),
TIME_TO_SEC('09:00'),
TIME_TO_SEC('09:00') - TIME_TO_SEC('09:02');
6. IFNULL 和 COALESCE 函数
SELECT
order_id,
IFNULL(shipper_id,'Not assigned') AS shipper
FROM orders;
SELECT
order_id,
COALESCE(shipper_id, comments,status,'Not assigned') AS shipper
FROM orders;
SELECT
CONCAT(first_name,' ',last_name) AS customer,
IFNULL(phone,'Unknown') AS phone
FROM customers;
7. IF 函数 只允许单一的条件表达式
SELECT
order_id,
IF(YEAR(order_date) = YEAR(NOW()),
'Active',
'Archived') AS category
FROM orders;
SELECT
p.product_id,
p.name,
COUNT(*) AS orders,
IF(COUNT(*) > 1,
'Many times',
'Once') AS frequency
FROM products p
JOIN order_items oi USING(product_id)
GROUP BY product_id,name;
8. CASE 语句块 针对多个条件表达式返回不同值时使用
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;
|