目錄
1,日期函數
2,字符串函數
3,數學函數
1,日期函數
樣例:
? ? ? ? 獲得年月日
????????????????select current_date();
? ?? ? ?獲取時分秒
????????????????select current_time();
????????獲得時間戳
????????????????select current_timestamp();
????????在日期的基礎上加日期
? ? ? ? ? ? ? ? 在2025年4月27日增加10天:select date_add('2025-04-27', interval 10 day);
? ? ? ? ? ? ? ? 在指定日期上增加5個月:select date_add('2025-04-27', interval 5 month);
? ? ? ??在日期的基礎上減少時間
????????????????在2025年4月27日增加10天:select date_sub('2025-04-27', interval 10 day);
? ? ? ? ? ? ? ? 在指定日期上增加5個月:select date_sub('2025-04-27', interval 5 month);
????????計算兩個日期之間相差多少天
????????????????select datediff('2025-05-01', '2025-04-27');
? ? ? ? 在生日表中增添當前的日期
? ? ? ? ? ? ? ? 創建表結構:create table birthdays (id int primary key, birthday date);
? ? ? ? ? ? ? ? 插入數據:insert into birthdays (id,birthday) values (1,current_date());
? ? ? ? ? ? ? ? 注意:若類型合適,這里也可以插入now()、current_timestamp()。
? ? ? ? 顯示出表 birthdays 的生日日期
? ? ? ? ? ? ? ? 方式一:select date(birthday) from birthdays;
? ? ? ? ? ? ? ? 方式二:select birthday from birthdays;
? ? ? ? ? ? ? ? 注意:date(datetime)語句中,只會顯示 datetime 的日期部分,不會顯示時間。
2,字符串函數
樣例:
????????獲取 persons 表的 name 列的每一個數據的字符集:
????????????????select charset(name) from persons;
? ? ? ? 按照指定 "x生xxx的興趣是xxx..." 格式顯示出 persons 表的信息
? ? ? ? ? ? ? ? select concat(gender,'生',name,'的興趣是',hobby) from persons;
? ? ? ? 查詢表 persons 表中人的姓名所占的字節數
????????????????select length(name) from persons;
????????????????注意:length函數返回字符串長度,以字節為單位。如果是多字節字符則計算多? ? ? ? ? ? ? ? ? ?個字節數;如果是單字節字符則算作一個字節。比如:字母,數字算作一個字節,? ? ? ? ? ? ? ? ? 中文表示多個字節數(與字符集編碼有關)
? ? ? ? 將 student 表中?qq 列里的 1 替換成 2 ,將其顯示出(表中數據沒有改變)
????????????????select replace(qq, '1', '2') from student;
? ? ? ? 截取?student 表中?qq 列里的第二個字符到第三個字符,將其顯示出
????????????????select substring(qq,2,2) from student;
????????以首字母小寫的方式顯示出 student 表中所有人的姓名
????????????????select concat(lcase(stustring(name,1,1)), substring(name,2)) from student;
3,數學函數
樣例:
????????絕對值:select abs(-100.2);? ? ???????輸出100.2??
????????向上取整:select ceiling(23.04);? ? 輸出24
? ? ? ? 向下取整:select floor(23.7);? ? ? ? ?輸出23
????????保留2位小數位數(小數四舍五入):select format(12.3456, 2);? ? ? ?輸出12.35
????????產生隨機數:select rand();? ? ? ????????輸出一個[0.0, 1.0)范圍的數值
? ? ? ? 除了上面幾個幾種函數外,還有一種 user()、database() 顯示當前的用戶、數據庫函數。