MySQL 常用函數

MySQL 常用函數

1. 字符串函數

函數 功能
concat(s1,s2,…,sn) 連接s1,s2,…,sn爲一個字符串
insert(str,x,y,instr) 將字符串str從第x位置開始,y個字符長的子串替換爲字符串instr(位置從1開始)
lower(str) 將字符串str中的字符轉換成小寫
upper(str) 將字符串str中的字符轉換成大寫
left(str,x) 返回str最左邊的x個字符
right(str,x) 返回str最右邊的x個字符
lpad(str,n,pad) 用字符串pad對str最左邊進行填充,直到長度爲n個字符長度
rpad(str,n,pad) 用字符串pad對str最右邊進行填充,直到長度爲n個字符長度
ltrim(str) 去掉左側的空格
rtrim(str) 去掉右側的空格
trim(str) 去掉兩側的空格
repeat(str,n) 返回字符串str重複n次的結果
replace(str,a,b) 用b替換str中所有出現的a
strcmp(s1,s2) 比較兩個字符串s1,s2。返回1,0,-1
substring(str,x,y) 返回從字符串str的x位置起的y個字符長度的子串(位置從1開始)

2. 數值函數

函數 功能
abs(x) 絕對值
ceil(x) 返回大於x的最小整數值,即向上取整
floor(x) 返回小於x的最大整數值,即向下取整
mod(x,y) x對y取餘
rand() 返回0~1內的隨機值
round(x,y) 返回參數x的四捨五入的有y位小數的值
truncate(x,y) 返回數字x截斷爲y位小數的結果

eg.

mysql> select ceil(1.2), floor(1.2);
+-----------+------------+
| ceil(1.2) | floor(1.2) |
+-----------+------------+
|         2 |          1 |
+-----------+------------+
1 row in set (0.00 sec)

mysql> select ceil(-1.2), floor(-1.2);
+------------+-------------+
| ceil(-1.2) | floor(-1.2) |
+------------+-------------+
|         -1 |          -2 |
+------------+-------------+
1 row in set (0.00 sec)

mysql> select rand(), ceil(100*rand());
+--------------------+------------------+
| rand()             | ceil(100*rand()) |
+--------------------+------------------+
| 0.6494681040285789 |               24 |
+--------------------+------------------+
1 row in set (0.00 sec)

mysql> select round(1.2345,2), round(1.456, 2);
+-----------------+-----------------+
| round(1.2345,2) | round(1.456, 2) |
+-----------------+-----------------+
|            1.23 |            1.46 |
+-----------------+-----------------+
1 row in set (0.00 sec)

mysql> select round(1.2345,6), round(1.456, 6);
+-----------------+-----------------+
| round(1.2345,6) | round(1.456, 6) |
+-----------------+-----------------+
|        1.234500 |        1.456000 |
+-----------------+-----------------+
1 row in set (0.00 sec)

mysql> select strcmp('bb', 'aa'), strcmp('bb', 'bb'), strcmp('bb', 'cc');
+--------------------+--------------------+--------------------+
| strcmp('bb', 'aa') | strcmp('bb', 'bb') | strcmp('bb', 'cc') |
+--------------------+--------------------+--------------------+
|                  1 |                  0 |                 -1 |
+--------------------+--------------------+--------------------+
1 row in set (0.00 sec)

mysql> select truncate(1.2345, 3), truncate(1.2345, 6);
+---------------------+---------------------+
| truncate(1.2345, 3) | truncate(1.2345, 6) |
+---------------------+---------------------+
|               1.234 |            1.234500 |
+---------------------+---------------------+
1 row in set (0.00 sec)

3. 日期和時間函數

函數 功能
curdate() 返回當前日期
curtime() 返回當前時間
now() 返回當前日期和時間
unix_timestamp(date) 返回日期date的unix時間戳
from_unixtime(stamp) 返回時間戳stamp的日期值
week(date) 返回日期date爲一年中的第幾周
year(date) 返回date的年份
hour(time) 返回time的小時值
minute(time) 返回time的分鐘值
monthname(date) 顯示date的月份名
date_format(date,fmt) 格式化日期時間
date_add(date,INTERVAL expr type) 返回與所給日期date加上INTERVAL 時間段的日期
date_sub(date, INTERVAL expr type) 返回與所給日期date減去INTERVAL 時間段的日期
datediff(date1,date2) 計算兩個日期之間相差的天數。date1-date2的天數

eg.

mysql> select curdate();
+------------+
| curdate()  |
+------------+
| 2018-10-27 |
+------------+
1 row in set (0.00 sec)

mysql> select curtime();
+-----------+
| curtime() |
+-----------+
| 21:45:00  |
+-----------+
1 row in set (0.00 sec)

mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2018-10-27 21:45:22 |
+---------------------+
1 row in set (0.00 sec)

mysql> select unix_timestamp(now());
+-----------------------+
| unix_timestamp(now()) |
+-----------------------+
|            1540648073 |
+-----------------------+
1 row in set (0.00 sec)

mysql> select from_unixtime(1540648073);
+---------------------------+
| from_unixtime(1540648073) |
+---------------------------+
| 2018-10-27 21:47:53       |
+---------------------------+
1 row in set (0.00 sec)

mysql> select week(now());
+-------------+
| week(now()) |
+-------------+
|          42 |
+-------------+
1 row in set (0.00 sec)

mysql> select year(now());
+-------------+
| year(now()) |
+-------------+
|        2018 |
+-------------+
1 row in set (0.00 sec)

mysql> select hour(now());
+-------------+
| hour(now()) |
+-------------+
|          22 |
+-------------+
1 row in set (0.00 sec)

mysql> select minute(now());
+---------------+
| minute(now()) |
+---------------+
|             4 |
+---------------+
1 row in set (0.00 sec)

mysql> select monthname(now());
+------------------+
| monthname(now()) |
+------------------+
| October          |
+------------------+
1 row in set (0.00 sec)

date_format(date, fmt):

按照字符串fmt 格式化日期 date 值,此函數能夠按指定的格式顯示日期,可以用到的格式符如下表顯示:

格式符 格式說明
%S和%s 兩位數字形式的秒(00,01,…,59)
%i 兩位數字形式的分(00,01,…,59)
%H 兩位數字形式的小時,24小時(00,01,…,23)
%h和%I(大寫i) 兩位數字形式的小時,12小時(01,02,…,12)
%k 數字形式的小時,24小時(0,1,…,23)
%l(小寫L) 數字形式的小時,12小時(1,2,…,12)
%T 24小時的時間形式(hh:mm:ss)
%r 12小時的時間格式(hh:mm:ssAM或hh:mm:ssPM)
%p AM 或 PM
%W 一週中每一天的名稱(Sunday,Monday,…,Saturday)
%a 一週中每一天名稱的縮寫(Sun,Mon,…,Sat)
%w 以數字形式表示週中的天數(0=Sunday,1=Monday,…,6=Saturday)
%d 兩位數字表示月中的天數(01,…,31)
%e 數字形式表示月中的天數(1,2,…,31)
%D 英文後綴表示月中的天數(1st,2nd,3rd,…)
%j 以3位數字表示年中的天數(001,002,…,366)
%U 一年中的第幾周(00,01,…,52),其中Sunday爲週中的第一天。(從00開始)
%u 一年中的第幾周(01,02,…,53),其中Monday爲週中的第一天。(從01開始)
%M 月名(January,February,…,December)
%b 縮寫的月名(Jan,Feb,…,Dec)
%m 兩位數字表示的月份(01,02,…,12)
%c 數字表示的月份(1,2,…,12)
%Y 4位數字表示的年份(2018)
%y 兩位數字表示的年份(18)

eg.

mysql> select date_format(now(), '%M, %D, %Y');
+----------------------------------+
| date_format(now(), '%M, %D, %Y') |
+----------------------------------+
| October, 27th, 2018              |
+----------------------------------+
1 row in set (0.00 sec)

時間:

mysql> select date_format(now(), '%H:%i:%S, %H:%i:%s');
+------------------------------------------+
| date_format(now(), '%H:%i:%S, %H:%i:%s') |
+------------------------------------------+
| 23:27:02, 23:27:02                       |
+------------------------------------------+
1 row in set (0.00 sec)

mysql> select date_format(now(), '%h:%i:%S %p, %I:%i:%S %p');
+------------------------------------------------+
| date_format(now(), '%h:%i:%S %p, %I:%i:%S %p') |
+------------------------------------------------+
| 11:27:54 PM, 11:27:54 PM                       |
+------------------------------------------------+
1 row in set (0.00 sec)

mysql> select date_format(now(), '%k:%i:%S, %l:%i:%S %p');
+---------------------------------------------+
| date_format(now(), '%k:%i:%S, %l:%i:%S %p') |
+---------------------------------------------+
| 23:28:57, 11:28:57 PM                       |
+---------------------------------------------+
1 row in set (0.00 sec)

mysql> select date_format(now(), '%T, %r');
+------------------------------+
| date_format(now(), '%T, %r') |
+------------------------------+
| 23:29:32, 11:29:32 PM        |
+------------------------------+
1 row in set (0.00 sec)

星期幾:

mysql> select date_format(now(), '%W %a %w');
+--------------------------------+
| date_format(now(), '%W %a %w') |
+--------------------------------+
| Saturday Sat 6                 |
+--------------------------------+
1 row in set (0.00 sec)

日期天數:

mysql> select date_format(now(), '%d, %e, %D');
+----------------------------------+
| date_format(now(), '%d, %e, %D') |
+----------------------------------+
| 27, 27, 27th                     |
+----------------------------------+
1 row in set (0.00 sec)

第幾天和第幾周:

mysql> select date_format('2018-01-01', '%j, %U, %u, %W');
+---------------------------------------------+
| date_format('2018-01-01', '%j, %U, %u, %W') |
+---------------------------------------------+
| 001, 00, 01, Monday                         |
+---------------------------------------------+
1 row in set (0.00 sec)

mysql> select date_format('2018-12-31', '%j, %U, %u, %W');
+---------------------------------------------+
| date_format('2018-12-31', '%j, %U, %u, %W') |
+---------------------------------------------+
| 365, 52, 53, Monday                         |
+---------------------------------------------+
1 row in set (0.00 sec)

月份名:

mysql> select date_format('2018-01-01', '%M, %b, %m, %c');
+---------------------------------------------+
| date_format('2018-01-01', '%M, %b, %m, %c') |
+---------------------------------------------+
| January, Jan, 01, 1                         |
+---------------------------------------------+
1 row in set (0.00 sec)

年份:

mysql> select date_format('2018-01-01', '%Y, %y');
+-------------------------------------+
| date_format('2018-01-01', '%Y, %y') |
+-------------------------------------+
| 2018, 18                            |
+-------------------------------------+
1 row in set (0.00 sec)

date_add(date, interval expr type) 函數: 返回與所給日期 date 相差 INTERVAL 的時間段的日期。

其中 INTERVAL 是間隔類型的關鍵字,expr 是一個表達式,正數表示向後加這個間隔,負數則表示向前減去這個間隔。這個表達式對應後面的類型,type 是間隔類型,MySQL 提供了 13 種間隔類型,如下表:

表達式類型 描述
hour 小時
minute 分鐘
second
year
month
day
year_month 年和月
day_hour 日和小時
day_minute 日和分鐘
day_second 日和秒
hour_minute 小時和分鐘
hour_second 小時和秒
minute_second 分鐘和秒

eg.

mysql> select now() current, date_add(now(), interval 1 hour) after1hour;
+---------------------+---------------------+
| current             | after1hour          |
+---------------------+---------------------+
| 2018-10-28 11:22:24 | 2018-10-28 12:22:24 |
+---------------------+---------------------+
1 row in set (0.00 sec)

mysql> select now() current, date_add(now(), interval 1 minute) after1minute;
+---------------------+---------------------+
| current             | after1minute        |
+---------------------+---------------------+
| 2018-10-28 11:22:43 | 2018-10-28 11:23:43 |
+---------------------+---------------------+
1 row in set (0.00 sec)

mysql> select now() current, date_add(now(), interval 1 second) after1second;
+---------------------+---------------------+
| current             | after1second        |
+---------------------+---------------------+
| 2018-10-28 11:23:13 | 2018-10-28 11:23:14 |
+---------------------+---------------------+
1 row in set (0.00 sec)

mysql> select now() current, date_add(now(), interval 1 year) after1year;
+---------------------+---------------------+
| current             | after1year          |
+---------------------+---------------------+
| 2018-10-28 11:23:43 | 2019-10-28 11:23:43 |
+---------------------+---------------------+
1 row in set (0.00 sec)

mysql> select now() current, date_add(now(), interval 1 month) after1month;
+---------------------+---------------------+
| current             | after1month         |
+---------------------+---------------------+
| 2018-10-29 21:39:03 | 2018-11-29 21:39:03 |
+---------------------+---------------------+
1 row in set (0.00 sec)

mysql> select now() current, date_add(now(), interval 1 day) after1day;
+---------------------+---------------------+
| current             | after1day           |
+---------------------+---------------------+
| 2018-10-29 21:39:14 | 2018-10-30 21:39:14 |
+---------------------+---------------------+
1 row in set (0.00 sec)

mysql> select now() current, date_add(now(), interval '1_1' year_month) after1year1month;
+---------------------+---------------------+
| current             | after1year1month    |
+---------------------+---------------------+
| 2018-10-28 11:26:11 | 2019-11-28 11:26:11 |
+---------------------+---------------------+
1 row in set (0.00 sec)

mysql> select now() current, date_add(now(), interval '-1_-1' year_month) before1year1month;
+---------------------+---------------------+
| current             | before1year1month   |
+---------------------+---------------------+
| 2018-10-28 11:30:42 | 2017-09-28 11:30:42 |
+---------------------+---------------------+
1 row in set (0.00 sec)

mysql> select now() current, date_add(now(), interval '1_1' day_hour) after1day1hour;
+---------------------+---------------------+
| current             | after1day1hour      |
+---------------------+---------------------+
| 2018-10-28 11:31:15 | 2018-10-29 12:31:15 |
+---------------------+---------------------+
1 row in set (0.00 sec)

mysql> select now() current, date_add(now(), interval '1_1' day_minute) after1day1minute;
+---------------------+---------------------+
| current             | after1day1minute    |
+---------------------+---------------------+
| 2018-10-28 11:31:29 | 2018-10-28 12:32:29 |
+---------------------+---------------------+
1 row in set (0.00 sec)

mysql> select now() current, date_add(now(), interval '1_1' day_second) after1day1second;
+---------------------+---------------------+
| current             | after1day1second    |
+---------------------+---------------------+
| 2018-10-28 11:31:42 | 2018-10-28 11:32:43 |
+---------------------+---------------------+
1 row in set (0.00 sec)

mysql> select now() current, date_add(now(), interval '1_1' hour_minute) after1hour1minute;
+---------------------+---------------------+
| current             | after1hour1minute   |
+---------------------+---------------------+
| 2018-10-28 11:32:04 | 2018-10-28 12:33:04 |
+---------------------+---------------------+
1 row in set (0.00 sec)

mysql> select now() current, date_add(now(), interval '1_1' hour_second) after1hour1second;
+---------------------+---------------------+
| current             | after1hour1second   |
+---------------------+---------------------+
| 2018-10-28 11:32:29 | 2018-10-28 11:33:30 |
+---------------------+---------------------+
1 row in set (0.00 sec)

mysql> select now() current, date_add(now(), interval '1_1' minute_second) after1minute1second;
+---------------------+---------------------+
| current             | after1minute1second |
+---------------------+---------------------+
| 2018-10-28 11:32:44 | 2018-10-28 11:33:45 |
+---------------------+---------------------+
1 row in set (0.00 sec)

date_sub(date, INTERVAL expr type):返回與所給日期date減去INTERVAL 時間段的日期。

eg.

mysql> select now() current, date_sub(now(), interval 1 day) before1day;
+---------------------+---------------------+
| current             | before1day          |
+---------------------+---------------------+
| 2018-10-29 21:40:09 | 2018-10-28 21:40:09 |
+---------------------+---------------------+
1 row in set (0.00 sec)

datediff(date1, date2): 計算兩個日期之間相差的天數。date1-date2

eg. 表示當前距離2010-09-14已經過去了2966天。

mysql> select now() current, datediff(now(), '2010-09-14');
+---------------------+-------------------------------+
| current             | datediff(now(), '2010-09-14') |
+---------------------+-------------------------------+
| 2018-10-28 11:35:02 |                          2966 |
+---------------------+-------------------------------+
1 row in set (0.00 sec)

4. 流程函數

流程函數也是很常用的一類函數,用戶可以使用這類函數在一個SQL語句中實現條件選擇,這樣做能夠提高語句的效率。

MySQL 中的流程函數

函數 功能
if(value, t, f) 如果 value 是真,返回t;否則返回f
ifnull(value1, value2) 如果 value1 不爲空,返回value1,否則返回 value2
case when [value1] then [result]…else[default] end 多條件判斷,見eg.相當於if…else if… else if … else
case [expr] when [value] then [result]…else[default] end 多值判斷,見eg. case A…;case B…;… default

eg.

創建職員薪水錶:

mysql> create table salary(userid int, salary decimal(9,2));
Query OK, 0 rows affected (0.08 sec)

mysql> insert into salary values(1,1000),(2,2000),(3,3000),(4,4000),(5,5000),(1,null);
Query OK, 6 rows affected (0.03 sec)
Records: 6  Duplicates: 0  Warnings: 0

mysql> select * from salary;
+--------+---------+
| userid | salary  |
+--------+---------+
|      1 | 1000.00 |
|      2 | 2000.00 |
|      3 | 3000.00 |
|      4 | 4000.00 |
|      5 | 5000.00 |
|      1 |    NULL |
+--------+---------+
6 rows in set (0.00 sec)

各個函數:

mysql> select if(salary > 2000, 'high','low') from salary;
+---------------------------------+
| if(salary > 2000, 'high','low') |
+---------------------------------+
| low                             |
| low                             |
| high                            |
| high                            |
| high                            |
| low                             |
+---------------------------------+
6 rows in set (0.00 sec)

mysql> select ifnull(salary,0) from salary;
+------------------+
| ifnull(salary,0) |
+------------------+
|          1000.00 |
|          2000.00 |
|          3000.00 |
|          4000.00 |
|          5000.00 |
|             0.00 |
+------------------+
6 rows in set (0.00 sec)

mysql> select case when salary<=2000 then 'low'  when salary<=3000 then 'middle' else 'high' end from salary;
+------------------------------------------------------------------------------------+
| case when salary<=2000 then 'low'  when salary<=3000 then 'middle' else 'high' end |
+------------------------------------------------------------------------------------+
| low                                                                                |
| low                                                                                |
| middle                                                                             |
| high                                                                               |
| high                                                                               |
| high                                                                               |
+------------------------------------------------------------------------------------+
6 rows in set (0.00 sec)

mysql> select case salary when 1000 then 'low'  when 2000 then 'middle' else 'high' end from salary;
+---------------------------------------------------------------------------+
| case salary when 1000 then 'low'  when 2000 then 'middle' else 'high' end |
+---------------------------------------------------------------------------+
| low                                                                       |
| middle                                                                    |
| high                                                                      |
| high                                                                      |
| high                                                                      |
| high                                                                      |
+---------------------------------------------------------------------------+
6 rows in set (0.00 sec)

5. 其他常用函數

函數 功能
datebase() 返回當前數據庫名
version() 返回當前數據庫版本
user() 返回當前登錄用戶名
inet_aton(ip) 返回ip地址的數字表示
inet_ntoa(num) 返回數字代表的ip地址
password(str)(8.0.11版本已經移除該函數) 返回字符串str的加密版本
md5(str) 返回字符串str的md5值

eg.

mysql> select database();
+------------+
| database() |
+------------+
| db201810   |
+------------+
1 row in set (0.00 sec)

mysql> select version();
+-----------+
| version() |
+-----------+
| 8.0.11    |
+-----------+
1 row in set (0.00 sec)

mysql> select user();
+--------------------+
| user()             |
+--------------------+
| bearyang@localhost |
+--------------------+
1 row in set (0.00 sec)

mysql> select inet_aton('192.168.1.2');
+--------------------------+
| inet_aton('192.168.1.2') |
+--------------------------+
|               3232235778 |
+--------------------------+
1 row in set (0.00 sec)

mysql> select inet_ntoa(3232235778);
+-----------------------+
| inet_ntoa(3232235778) |
+-----------------------+
| 192.168.1.2           |
+-----------------------+
1 row in set (0.01 sec)

# 8.0.11 版本
mysql> select password('123456');
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '('123456')' at line 1

# 5.7.22 版本
mysql> select password('123456');
+-------------------------------------------+
| password('123456')                        |
+-------------------------------------------+
| *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 |
+-------------------------------------------+
1 row in set, 1 warning (0.00 sec)

mysql> select md5('123456');
+----------------------------------+
| md5('123456')                    |
+----------------------------------+
| e10adc3949ba59abbe56e057f20f883e |
+----------------------------------+
1 row in set (0.00 sec)

MySQL 系列:

1. MySQL 常用 SQL 命令(1. DDL語句)

2. MySQL 常用 SQL 命令(2. DML語句)

3. MySQL 常用函數

更多文章

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章