MySQL数据库函数是预定义的SQL语句,可以对数据进行操作和处理。以下是一些常用的MySQL函数及其使用方法:
示例:
SELECT CONCAT('Hello, ', 'World!') AS result; -- 结果:Hello, World!
SELECT LEFT('Hello, World!', 5) AS result; -- 结果:Hello
SELECT RIGHT('Hello, World!', 5) AS result; -- 结果:World!
SELECT SUBSTRING('Hello, World!', 7, 5) AS result; -- 结果:World
SELECT LOWER('Hello, World!') AS result; -- 结果:hello, world!
SELECT UPPER('Hello, World!') AS result; -- 结果:HELLO, WORLD!
SELECT TRIM(' Hello, World! ') AS result; -- 结果:Hello, World!
示例:
SELECT ROUND(3.14159, 2) AS result; -- 结果:3.14
SELECT CEILING(3.14159) AS result; -- 结果:4
SELECT FLOOR(3.14159) AS result; -- 结果:3
SELECT ABS(-3.14159) AS result; -- 结果:3.14159
SELECT MOD(7, 3) AS result; -- 结果:1
示例:
SELECT NOW() AS result; -- 结果:当前日期和时间(例如:2023-10-05 14:30:00)
SELECT CURDATE() AS result; -- 结果:当前日期(例如:2023-10-05)
SELECT CURTIME() AS result; -- 结果:当前时间(例如:14:30:00)
SELECT STR_TO_DATE('2023-10-05', '%Y-%m-%d') AS result; -- 结果:2023-10-05
SELECT DATEDIFF('2023-10-06', '2023-10-05') AS result; -- 结果:1
SELECT DATE_ADD('2023-10-05', INTERVAL 1 DAY) AS result; -- 结果:2023-10-06
SELECT DATE_SUB('2023-10-05', INTERVAL 1 DAY) AS result; -- 结果:2023-10-04
示例:
SELECT COUNT(*) AS result FROM students; -- 结果:学生数量
SELECT SUM(score) AS result FROM scores; -- 结果:所有学生的总分
SELECT AVG(score) AS result FROM scores; -- 结果:所有学生的平均分
SELECT MIN(score) AS result FROM scores; -- 结果:最低分
SELECT MAX(score) AS result FROM scores; -- 结果:最高分
SELECT GROUP_CONCAT(student_name ORDER BY score DESC SEPARATOR ', ') AS result FROM scores; -- 结果:按分数降序排列的学生姓名列表
这些只是MySQL函数的一部分,还有其他函数可用于更复杂的数据处理。在使用函数时,请确保了解函数的功能、参数和返回值,并根据需要选择合适的函数。