MySQL是一個開源的關系型數(shù)據(jù)庫管理系統(tǒng),廣泛應用于網(wǎng)站開發(fā)、數(shù)據(jù)分析等領域。MySQL提供了豐富的內(nèi)置函數(shù)來簡化數(shù)據(jù)處理的代碼量,本文將介紹一些常用的MySQL數(shù)據(jù)庫內(nèi)置函數(shù)。
字符串函數(shù)
MySQL提供了很多字符串處理的內(nèi)置函數(shù),例如:
SELECT UPPER('hello') AS upper; -- 轉換為大寫 SELECT LOWER('HELLO') AS lower; -- 轉換為小寫 SELECT SUBSTRING('hello', 2, 3) AS substring; -- 截取字符串(從第2個字符開始,截取3個字符) SELECT REPLACE('hello, world', 'hello', 'hi') AS replace; -- 替換字符串(將‘hello’替換為‘hi’) SELECT TRIM(' hello ') AS trim; -- 去除字符串兩端的空格
數(shù)值函數(shù)
MySQL提供了很多數(shù)值處理的內(nèi)置函數(shù),例如:
SELECT ABS(-1) AS abs; -- 絕對值 SELECT RAND() AS rand; -- 隨機數(shù) SELECT ROUND(1.234567, 2) AS round; -- 舍入(保留2位小數(shù)) SELECT FLOOR(3.7) AS floor; -- 向下取整 SELECT CEILING(1.2) AS ceiling; -- 向上取整 SELECT MOD(9, 4) AS mod; -- 取模(返回9/4的余數(shù))
日期和時間函數(shù)
MySQL提供了很多日期和時間處理的內(nèi)置函數(shù),例如:
SELECT NOW() AS now; -- 返回當前日期和時間 SELECT DATE(NOW()) AS date; -- 返回當前日期 SELECT TIME(NOW()) AS time; -- 返回當前時間 SELECT YEAR(NOW()) AS year; -- 返回當前年份 SELECT MONTH(NOW()) AS month; -- 返回當前月份 SELECT DAY(NOW()) AS day; -- 返回當前日 SELECT HOUR(NOW()) AS hour; -- 返回當前小時數(shù) SELECT MINUTE(NOW()) AS minute; -- 返回當前分鐘數(shù) SELECT SECOND(NOW()) AS second; -- 返回當前秒數(shù) SELECT DAYNAME(NOW()) AS dayname; -- 返回今天是星期幾 SELECT DATE_ADD(NOW(), INTERVAL 1 DAY) AS addDay; -- 增加1天 SELECT DATE_SUB(NOW(), INTERVAL 1 DAY) AS subDay; -- 減少1天
邏輯函數(shù)
MySQL提供了很多邏輯處理的內(nèi)置函數(shù),例如:
SELECT IF(1 = 1, 'true', 'false') AS if; -- 判斷條件 SELECT CASE 2 WHEN 1 THEN 'one' WHEN 2 THEN 'two' ELSE 'other' END AS case; -- 多分支判斷 SELECT COALESCE(NULL, 1) AS coalesce; -- 返回第一個非空值 SELECT NULLIF(1, 1) AS nullif; -- 如果兩個值相等,則返回NULL SELECT GREATEST(1, 2, 3) AS greatest; -- 返回最大值 SELECT LEAST(1, 2, 3) AS least; -- 返回最小值
以上僅是MySQL內(nèi)置函數(shù)的一部分,更多的MySQL內(nèi)置函數(shù)請查閱官方文檔。