MySQL經常使用函數介紹

1、操做符優先級

    下面展現了全部操做符的執行優先級,從高到低,同一行中的操做符優先級相同,相同優先級的狀況下從左到右執行。html

INTERVAL

BINARY, COLLATE

!

- (unary minus), ~ (unary bit inversion)

^

*, /, DIV, %, MOD

-, +

<<, >>

&

|

= (comparison), <=>, >=, >, <=, <, <>, !=, IS, LIKE, REGEXP, IN

BETWEEN, CASE, WHEN, THEN, ELSE

NOT

AND, &&

XOR

OR, ||

= (assignment), :=

 

  • 若是想改變優先級執行順序,則可使用括號。
mysql> select 1+2*3;

+-------+

| 1+2*3 |

+-------+

|     7 |

+-------+

1 row in set (0.00 sec)

 

mysql> select (1+2)*3;

+---------+

| (1+2)*3 |

+---------+

|       9 |

+---------+

1 row in set (0.00 sec)

 

2、比較函數

名稱mysql

描述sql

安全

大於運算符函數

>=測試

大於或等於運算符ui

spa

少於運算符unix

<>, !=code

不等於運算符

<=

小於或等於運算符

<=>

NULL安全等於運算符

=

平等算子

BETWEEN ... AND ...

值是否在值範圍內

COALESCE()

返回第一個非NULL參數

GREATEST()

返回最大參數

IN()

一個值是否在一組值內

INTERVAL()

返回小於第一個參數的參數的索引

IS

針對布爾值測試值

IS NOT

針對布爾值測試值

IS NOT NULL

非空值測試

IS NULL

空值測試

ISNULL()

測試參數是否爲NULL

LEAST()

返回最小的參數

LIKE

簡單模式匹配

NOT BETWEEN ... AND ...

值是否不在值範圍內

NOT IN()

一個值是否不在一組值內

NOT LIKE

否認簡單模式匹配

STRCMP()

比較兩個字符串

 

  • 對比操做符的執行結果爲true,false,null三種。
  • between A and B表明檢查值是否在A和B之間。
mysql> select * from students;

+-----+-------+--------+---------+

| sid | sname | gender | dept_id |

+-----+-------+--------+---------+

|   1 | a     | 3      |       4 |

|   4 | c     | 3      |       1 |

|   5 | d     | 1      |       2 |

|   6 | e     | 2      |       4 |

+-----+-------+--------+---------+

4 rows in set (0.00 sec) mysql> select * from students where sid between 3 and 5;##該語句至關於下面的那個語句。 +-----+-------+--------+---------+ | sid | sname | gender | dept_id | +-----+-------+--------+---------+ | 4 | c | 3 | 1 | | 5 | d | 1 | 2 | +-----+-------+--------+---------+ 2 rows in set (0.00 sec) mysql> select * from students where sid>=3 and sid<=5; +-----+-------+--------+---------+ | sid | sname | gender | dept_id | +-----+-------+--------+---------+ | 4 | c | 3 | 1 | | 5 | d | 1 | 2 | +-----+-------+--------+---------+ 2 rows in set (0.00 sec)

 

  • COALESCE(value,...)對比操做符

         返回第一個非NULL的值,若是沒有非null值,則返回NULL

mysql> SELECT COALESCE(NULL,2);

 -> 2 mysql> SELECT COALESCE(NULL,NULL,NULL); -> NULL

 

  • =表明相等操做符。
  • >表明大於操做符。
  • >=表明大於等於操做符。
  • greatest()表明返回最大的值。
mysql> select greatest(1,5,10,2);

+--------------------+

| greatest(1,5,10,2) |

+--------------------+

|                 10 |

+--------------------+

1 row in set (0.00 sec)

 

  • lnterval()表明返回比第一個參數小的參數的位置。
  • is/is not表明檢查值是否與布爾值相同/不一樣。
mysql> SELECT 1 IS TRUE, 0 IS FALSE, NULL IS UNKNOWN;

+-----------+------------+-----------------+

| 1 IS TRUE | 0 IS FALSE | NULL IS UNKNOWN |

+-----------+------------+-----------------+

|         1 |          1 |               1 |

+-----------+------------+-----------------+

1 row in set (0.00 sec) mysql> SELECT 1 IS NOT UNKNOWN, 0 IS NOT UNKNOWN, NULL IS NOT UNKNOWN; +------------------+------------------+---------------------+ | 1 IS NOT UNKNOWN | 0 IS NOT UNKNOWN | NULL IS NOT UNKNOWN | +------------------+------------------+---------------------+ | 1 | 1 | 0 | +------------------+------------------+---------------------+ 1 row in set (0.00 sec)

 

  • is not null表明檢查值是不是非NULL。
mysql> select * from students;

+-----+--------+--------+---------+---------------------+

| sid | sname  | gender | dept_id | brithday            |

+-----+--------+--------+---------+---------------------+

|   1 | Andrew | 0      |       1 | 1983-01-01 00:00:00 |

|   2 | Andy   | 0      |       1 | 1983-01-01 00:00:00 |

|   3 | Bob    | 0      |       1 | 1983-01-01 00:00:00 |

|   4 | Ruth   | 1      |       2 | 1983-01-01 00:00:00 |

|   5 | Mike   | 0      |       2 | 1986-01-01 00:00:00 |

|   6 | John   | 0      |       3 | 1986-01-01 00:00:00 |

|   7 | Cindy  | 1      |       3 | 1986-01-01 00:00:00 |

|   8 | Susan  | 1      |       3 | 1986-01-01 00:00:00 |

|   9 | NULL   | 0      |       1 | NULL                |

+-----+--------+--------+---------+---------------------+

9 rows in set (0.00 sec) mysql> select * from students where sname is not null; +-----+--------+--------+---------+---------------------+ | sid | sname | gender | dept_id | brithday | +-----+--------+--------+---------+---------------------+ | 1 | Andrew | 0 | 1 | 1983-01-01 00:00:00 | | 2 | Andy | 0 | 1 | 1983-01-01 00:00:00 | | 3 | Bob | 0 | 1 | 1983-01-01 00:00:00 | | 4 | Ruth | 1 | 2 | 1983-01-01 00:00:00 | | 5 | Mike | 0 | 2 | 1986-01-01 00:00:00 | | 6 | John | 0 | 3 | 1986-01-01 00:00:00 | | 7 | Cindy | 1 | 3 | 1986-01-01 00:00:00 | | 8 | Susan | 1 | 3 | 1986-01-01 00:00:00 | +-----+--------+--------+---------+---------------------+ 8 rows in set (0.00 sec)

 

  • is null表明檢查值是不是NULL。
mysql> select * from students;

+-----+--------+--------+---------+---------------------+

| sid | sname  | gender | dept_id | brithday            |

+-----+--------+--------+---------+---------------------+

|   1 | Andrew | 0      |       1 | 1983-01-01 00:00:00 |

|   2 | Andy   | 0      |       1 | 1983-01-01 00:00:00 |

|   3 | Bob    | 0      |       1 | 1983-01-01 00:00:00 |

|   4 | Ruth   | 1      |       2 | 1983-01-01 00:00:00 |

|   5 | Mike   | 0      |       2 | 1986-01-01 00:00:00 |

|   6 | John   | 0      |       3 | 1986-01-01 00:00:00 |

|   7 | Cindy  | 1      |       3 | 1986-01-01 00:00:00 |

|   8 | Susan  | 1      |       3 | 1986-01-01 00:00:00 |

|   9 | NULL   | 0      |       1 | NULL                |

+-----+--------+--------+---------+---------------------+

9 rows in set (0.00 sec) mysql> select * from students where sname='null'; Empty set (0.00 sec) mysql> select * from students where sname is null; +-----+-------+--------+---------+----------+ | sid | sname | gender | dept_id | brithday | +-----+-------+--------+---------+----------+ | 9 | NULL | 0 | 1 | NULL | +-----+-------+--------+---------+----------+ 1 row in set (0.00 sec)

 

<表明小於操做符。

<=表明小於等於操做符。

like表明字符匹配。

not between A and B表明檢查值是否不在A和B的範圍以內。

!=/<>表明不等於操做符。

mysql> select * from students;

+-----+-------+--------+---------+

| sid | sname | gender | dept_id |

+-----+-------+--------+---------+

|   1 | a     | 3      |       4 |

|   4 | c     | 3      |       1 |

|   5 | d     | 1      |       2 |

|   6 | e     | 2      |       4 |

+-----+-------+--------+---------+

4 rows in set (0.00 sec) mysql> select * from students where sid!=6; +-----+-------+--------+---------+ | sid | sname | gender | dept_id | +-----+-------+--------+---------+ | 1 | a | 3 | 4 | | 4 | c | 3 | 1 | | 5 | d | 1 | 2 | +-----+-------+--------+---------+ 3 rows in set (0.00 sec) mysql> select * from students where sid<>6; +-----+-------+--------+---------+ | sid | sname | gender | dept_id | +-----+-------+--------+---------+ | 1 | a | 3 | 4 | | 4 | c | 3 | 1 | | 5 | d | 1 | 2 | +-----+-------+--------+---------+ 3 rows in set (0.00 sec)

 

  • not in()表明檢查值是否不在一系列值的當中。
  • not like表明檢查值是否不匹配。
  • strcmp()對比兩個字符串。
  • =號對比操做符。
mysql> select true;##在mysql中真用數字1表示。

+------+

| TRUE |

+------+

|    1 |

+------+

1 row in set (0.00 sec) mysql> select false;##在mysql中假用數字0表示。 +-------+ | FALSE | +-------+ | 0 | +-------+ 1 row in set (0.00 sec) mysql> select 1=0; +-----+ | 1=0 | +-----+ | 0 | +-----+ 1 row in set (0.01 sec) mysql> select 0=0; +-----+ | 0=0 | +-----+ | 1 | +-----+ 1 row in set (0.00 sec)

 

  • expr between min and max對比操做符。

         若是expr大於或等於min且expr小於或等於 max,則BETWEEN返回1,不然返回0。若是全部參數均爲同一類型。(min <= expr AND expr <= max)

mysql> SELECT 2 BETWEEN 1 AND 3, 2 BETWEEN 3 and 1;

    -> 1, 0 mysql> SELECT 1 BETWEEN 2 AND 3; -> 0 mysql> SELECT 'b' BETWEEN 'a' AND 'c'; -> 1 mysql> SELECT 2 BETWEEN 2 AND '3'; -> 1 mysql> SELECT 2 BETWEEN 2 AND 'x-3'; -> 0

 

  • expr NOT BETWEEN min AND max

         至關於NOT (expr BETWEEN min AND max)

  • expr IN (value,...)對比操做符。

         當expr值能在values中找到,則返回1,不然返回0。

mysql> SELECT 2 IN (0,3,5,7);

    -> 0 mysql> SELECT 'wefwf' IN ('wee','wefwf','weg'); -> 1 mysql> SELECT (3,4) IN ((1,2), (3,4)); -> 1 mysql> SELECT (3,4) IN ((1,2), (3,5)); -> 0 mysql> select * from students; +-----+-------+--------+---------+ | sid | sname | gender | dept_id | +-----+-------+--------+---------+ | 1 | a | 3 | 4 | | 4 | c | 3 | 1 | | 5 | d | 1 | 2 | | 6 | e | 2 | 4 | +-----+-------+--------+---------+ 4 rows in set (0.00 sec) mysql> select * from students where sid in (1,2,5,7,8);##要篩選的sid須要知足(1,2,5,7,8)中的任意一個。 +-----+-------+--------+---------+ | sid | sname | gender | dept_id | +-----+-------+--------+---------+ | 1 | a | 3 | 4 | | 5 | d | 1 | 2 | +-----+-------+--------+---------+ 2 rows in set (0.00 sec)

 

  • expr not IN (value,...)對比操做符。
  • lsnull(expr)操做符

    若是expr是null,則返回1,不然返回0、

mysql> select isnull(1+1);

+-------------+

| isnull(1+1) |

+-------------+

|           0 |

+-------------+

1 row in set (0.00 sec) mysql> select isnull(1/0); +-------------+ | isnull(1/0) | +-------------+ | 1 | +-------------+ 1 row in set (0.00 sec)

 

  • least(value1,value2,...)

    返回最小值,若是其中有值爲null,則返回null。

mysql> select least(0,-1,2);

+---------------+

| least(0,-1,2) |

+---------------+

|            -1 |

+---------------+

1 row in set (0.00 sec)

 

 

3、邏輯操做符

  • 邏輯操做符返回1(TRUE),0(FALSE),或者NULL。

name

description

AND,&&

logical and

NOT,!

negates value

||,OR

logical or

XOR

logical xor

 

  • NOT,!邏輯操做符表明非操做。
mysql> SELECT NOT 10;

 -> 0

mysql> SELECT NOT 0;

 -> 1

mysql> SELECT NOT NULL;

 -> NULL

mysql> SELECT ! (1+1);

 -> 0

mysql> SELECT ! 1+1;

 -> 1

 

  • And,&&邏輯操做符。
mysql> select * from students;

+-----+-------+--------+---------+

| sid | sname | gender | dept_id |

+-----+-------+--------+---------+

|   1 | a     | 3      |       4 |

|   4 | c     | 3      |       1 |

|   5 | d     | 1      |       2 |

|   6 | e     | 2      |       4 |

+-----+-------+--------+---------+

4 rows in set (0.00 sec)

 

mysql> select * from students where sid>3 and sid<7;

+-----+-------+--------+---------+

| sid | sname | gender | dept_id |

+-----+-------+--------+---------+

|   4 | c     | 3      |       1 |

|   5 | d     | 1      |       2 |

|   6 | e     | 2      |       4 |

+-----+-------+--------+---------+

3 rows in set (0.00 sec)

 

||,OR

mysql> select * from students;

+-----+-------+--------+---------+

| sid | sname | gender | dept_id |

+-----+-------+--------+---------+

|   1 | a     | 3      |       4 |

|   4 | c     | 3      |       1 |

|   5 | d     | 1      |       2 |

|   6 | e     | 2      |       4 |

+-----+-------+--------+---------+

4 rows in set (0.00 sec)

 

mysql> select * from students where sid>3 or sid<7;

+-----+-------+--------+---------+

| sid | sname | gender | dept_id |

+-----+-------+--------+---------+

|   1 | a     | 3      |       4 |

|   4 | c     | 3      |       1 |

|   5 | d     | 1      |       2 |

|   6 | e     | 2      |       4 |

+-----+-------+--------+---------+

4 rows in set (0.00 sec)

 

mysql> select * from students where sid>3 or sid<7 and sid>5;##因爲and的優先級高於or,因此先執行後半部分。

+-----+-------+--------+---------+

| sid | sname | gender | dept_id |

+-----+-------+--------+---------+

|   4 | c     | 3      |       1 |

|   5 | d     | 1      |       2 |

|   6 | e     | 2      |       4 |

+-----+-------+--------+---------+

3 rows in set (0.00 sec)

 

  • Xor邏輯操做符

         邏輯異或。NULL若是任一操做數爲,則返回NULL。對於非NULL操做數,計算 1出奇數個操做數是否爲非零,不然0返回。====>>>>不理解

https://dev.mysql.com/doc/refman/5.7/en/logical-operators.html#operator_xor

mysql> SELECT 1 XOR 1;

    -> 0

mysql> SELECT 1 XOR 0;

    -> 1

mysql> SELECT 1 XOR NULL;

    -> NULL

mysql> SELECT 1 XOR 1 XOR 1;

    -> 1

 

第1章 分配操做符

l  分配操做符是指賦值操做

name

description

=

assign a value(as part of a set statement,or as part of the set clause in an update statement)

:=

assign a value

mysql> select @a,@b;##默認值是空的。

+------+------+

| @a   | @b   |

+------+------+

| NULL | NULL |

+------+------+

1 row in set (0.01 sec)

 

mysql> select @a:=10,@b;##經過「:=」賦值a的值是10。

+--------+------+

| @a:=10 | @b   |

+--------+------+

|     10 | NULL |

+--------+------+

1 row in set (0.00 sec)

 

mysql> select @a;##查詢a的值。

+------+

| @a   |

+------+

|   10 |

+------+

1 row in set (0.00 sec)

mysql> set @a=17;##也可使用set命令來賦值。

Query OK, 0 rows affected (0.00 sec)

 

mysql> select @a;

+------+

| @a   |

+------+

|   17 |

+------+

1 row in set (0.00 sec)

l  =操做符在兩種狀況下會被認爲是賦值操做,而其餘狀況下會認爲是對比操做符

       在set語句中,=操做符會被認爲是賦值操做

mysql> set @a=1;

mysql> select @a;

+------+

| @a |

+------+

| 1 |

l  在update語句中的set子句中,=操做符會被認爲是賦值操做

 

1、算數運算符 

名稱

描述

%, MOD

模運算符

*

乘法運算符

+

加法運算符

-

減號

-

更改參數的符號

/

除法

DIV

整數除法

 

  • /表明除法
mysql> SELECT 3/5;

    -> 0.60

mysql> SELECT 102/(1-1);

    -> NULL

 

  • div表明整數型除法,相除以後只取整數部分
mysql> SELECT 5 DIV 2, -5 DIV 2, 5 DIV -2, -5 DIV -2;
    -> 2, -2, -2, 2

 

  • MOD(N,M), N % M, N MOD M

N % M,N MOD M模運算。返回N除以M的餘數。通常用在分片場景

mysql> SELECT MOD(234, 10);

        -> 4

mysql> SELECT 253 % 7;

        -> 1

mysql> SELECT MOD(29,9);

        -> 2

mysql> SELECT 29 MOD 9;

        -> 2

 

 

2、數字函數

名稱

描述

ABS()

返回絕對值

ACOS()

返回反餘弦

ASIN()

返回反正弦

ATAN()

返回反正切

ATAN2() ATAN()

返回兩個參數的反正切

CEIL()

返回不小於參數的最小整數值

CEILING()

返回不小於參數的最小整數值

CONV()

在不一樣的基數之間轉換數字

COS()

返回餘弦

COT()

返回餘切

CRC32()

計算循環冗餘校驗值

DEGREES()

將弧度轉換爲度

EXP()

提高力量

FLOOR()

返回不大於參數的最大整數值

LN()

返回參數的天然對數

LOG()

返回第一個參數的天然對數

LOG10()

返回參數的以10爲底的對數

LOG2()

返回參數的以2爲底的對數

MOD()

退還剩餘

PI()

返回pi的值

POW()

將參數提升到指定的冪

POWER()

將參數提升到指定的冪

RADIANS()

返回參數轉換爲弧度

RAND()

返回一個隨機浮點值

ROUND()

圍繞論點

SIGN()

返回參數的符號

SIN()

返回參數的正弦

SQRT()

返回參數的平方根

TAN()

返回參數的切線

TRUNCATE()

截斷爲指定的小數位數

 

  • ABS(X)

    絕對值函數。

mysql> SELECT ABS(2);

    -> 2

mysql> SELECT ABS(-32);

    -> 32

 

  • CEILING(X)/CEIL(X)

         返回>=X值的最小整數。

mysql> SELECT CEILING(1.23);

    -> 2

mysql> SELECT CEILING(-1.23);

    -> -1

 

  • FLOOR(X)

         返回<=X值的最大整數。

mysql> SELECT FLOOR(1.23), FLOOR(-1.23);

    -> 1, -2

 

  • RAND([N])

         獲取01之間的隨機小數,好比當想獲取7~12之間的隨機整數是可使用。通常用於生成測試數據

SELECT FLOOR(7 + (RAND() * 5));

select floor(10+(rand()*10));##取10-20的隨機整數

Select * from students order by rand() limit 1;

 

  • ROUND(X), ROUND(X,D)

         四捨五入爲D位個小數,當D參數不存在是,則默認爲0D 能夠爲負數,從而致使D該值的小數點左邊的數字,X變爲零。

mysql> SELECT ROUND(-1.23);

    -> -1

mysql> SELECT ROUND(-1.58);

    -> -2

mysql> SELECT ROUND(1.58);

    -> 2

mysql> SELECT ROUND(1.298, 1);

    -> 1.3

mysql> SELECT ROUND(1.298, 0);

    -> 1

mysql> SELECT ROUND(23.298, -1);

    -> 20

 

  • TRUNCATE(X,D)

         數字X只保留D位的小數,其他均捨棄。D能夠爲負數,從而致使D該值的小數點左邊的數字X變爲零。

mysql> SELECT TRUNCATE(1.223,1);

    -> 1.2

mysql> SELECT TRUNCATE(1.999,1);

    -> 1.9

mysql> SELECT TRUNCATE(1.999,0);

    -> 1

mysql> SELECT TRUNCATE(-1.999,1);

    -> -1.9

mysql> SELECT TRUNCATE(122,-2);

    -> 100

mysql> SELECT TRUNCATE(10.28*100,0);

    -> 1028

 

 

3、日期和時間函數

名稱

描述

ADDDATE()

將時間值(間隔)添加到日期值

ADDTIME()

加時間

CONVERT_TZ()

從一個時區轉換到另外一個時區

CURDATE()

返回當前日期

CURRENT_DATE(), CURRENT_DATE

CURDATE()的同義詞

CURRENT_TIME(),CURRENT_TIME

CURTIME()的同義詞

CURRENT_TIMESTAMP(),CURRENT_TIMESTAMP

NOW()的同義詞

CURTIME()

返回當前時間

DATE()

提取日期或日期時間表達式的日期部分

DATE_ADD()

將時間值(間隔)添加到日期值

DATE_FORMAT()

指定格式日期

DATE_SUB()

從日期中減去時間值(間隔)

DATEDIFF()

減去兩個日期

DAY()

DAYOFMONTH()的同義詞

DAYNAME()

返回工做日的名稱

DAYOFMONTH()

返回月份中的一天(0-31)

DAYOFWEEK()

返回參數的工做日索引

DAYOFYEAR()

返回一年中的某天(1-366)

EXTRACT()

提取部分日期

FROM_DAYS()

將天數轉換爲日期

FROM_UNIXTIME()

將Unix時間戳記格式化爲日期

GET_FORMAT()

返回日期格式字符串

HOUR()

提取時間

LAST_DAY

返回參數的月份的最後一天

LOCALTIME(), LOCALTIME

NOW()的同義詞

LOCALTIMESTAMP,LOCALTIMESTAMP()

NOW()的同義詞

MAKEDATE()

從一年中的年月日建立日期

MAKETIME()

從小時,分鐘,秒建立時間

MICROSECOND()

從參數返回微秒

MINUTE()

返回參數的分鐘

MONTH()

返回通過日期的月份

MONTHNAME()

返回月份名稱

NOW()

返回當前日期和時間

PERIOD_ADD()

在一年的月份中添加一個期間

PERIOD_DIFF()

返回期間之間的月數

QUARTER()

從日期參數返回季度

SEC_TO_TIME()

將秒轉換爲「 hh:mm:ss」格式

SECOND()

返回第二個(0-59)

STR_TO_DATE()

將字符串轉換爲日期

SUBDATE()

用三個參數調用時DATE_SUB()的同義詞

SUBTIME()

減去時間

SYSDATE()

返回函數執行的時間

TIME()

提取傳遞的表達式的時間部分

TIME_FORMAT()

格式化爲時間

TIME_TO_SEC()

返回參數轉換爲秒

TIMEDIFF()

減去時間

TIMESTAMP()

僅使用一個參數,此函數將返回日期或日期時間表達式。有兩個參數,參數的總和

TIMESTAMPADD()

向日期時間表達式添加間隔

TIMESTAMPDIFF()

從日期時間表達式中減去一個間隔

TO_DAYS()

返回日期參數轉換爲天

TO_SECONDS()

返回從Year 0開始轉換爲秒的日期或datetime參數

UNIX_TIMESTAMP()

返回Unix時間戳

UTC_DATE()

返回當前UTC日期

UTC_TIME()

返回當前UTC時間

UTC_TIMESTAMP()

返回當前UTC日期和時間

WEEK()

返回星期數

WEEKDAY()

返回工做日索引

WEEKOFYEAR()

返回日期的日曆周(1-53)

YEAR()

返回年份

YEARWEEK()

返回年和周

 

  •  ADDDATE(date,INTERVAL expr unit),ADDDATE(expr,days)

         當expr爲正數時則爲增長時間,爲負數時則爲減小時間。Unit參數能夠是任意時間單位

mysql> SELECT ADDDATE('2008-01-02', INTERVAL 31 DAY);

    -> '2008-02-02'

mysql> SELECT ADDDATE('2008-01-02', 31);

    -> '2008-02-02'

 

  • ADDTIME(expr1,expr2)

         將expr2的時間增長到expr1上

mysql> SELECT ADDTIME('2007-12-31 23:59:59.999999', '1 1:1:1.000002');

    -> '2008-01-02 01:01:01.000001'

mysql> SELECT ADDTIME('01:00:00.999999', '02:00:00.999998');

    -> '03:00:01.999997'

 

  • CONVERT_TZ(dt,from_tz,to_tz)

         將時間dt從from_tz這個時區轉換成to_tz這個時區並返回

mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','GMT','MET');

    -> '2004-01-01 13:00:00'

mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00');

    -> '2004-01-01 22:00:00‘

 

  • CURDATE(),CURRENT_DATE,CURRENT_DATE()

         返回以yyyy-mm-dd或者yyyymmdd格式的當前日期

mysql> SELECT CURDATE();

    -> '2008-06-13'

mysql> SELECT CURDATE() + 0;

    -> 20080613

 

  • CURTIME(),CURRENT_TIME,CURRENT_TIME()

         按照hh:mm:ss或者hhmmss格式返回當前時間

mysql> SELECT CURTIME();

    -> '23:50:26'

mysql> SELECT CURTIME() + 0;

    -> 235026.000000

 

  • Now(), CURRENT_TIMESTAMP,CURRENT_TIMESTAMP()

         返回當前的日期和時間,格式爲yyyy-mm-dd hh:mi:ss或者yyyymmddhhmiss

mysql> SELECT NOW();

    -> '2007-12-15 23:50:26'

mysql> SELECT NOW() + 0;

    -> 20071215235026.000000

 

  • DATE(expr)

         獲取expr中的日期

mysql> SELECT DATE('2003-12-31 01:02:03');

-> '2003-12-31'

 

  • YEAR(expr)

         獲取expr中的年份

mysql> select year('2020-01-15 19:41:57');

+-----------------------------+

| year('2020-01-15 19:41:57') |

+-----------------------------+

|                        2020 |

+-----------------------------+

1 row in set (0.00 sec)

 

  • DATEDIFF(expr1,expr2)

         返回expr1和expr2之間的天數差別,忽略時分秒

mysql> SELECT DATEDIFF('2007-12-31 23:59:59','2007-12-30');

    -> 1

mysql> SELECT DATEDIFF('2010-11-30 23:59:59','2010-12-31');

    -> -31

 

  • DATE_ADD(date,INTERVAL expr unit), DATE_SUB(date,INTERVAL expr unit

         增長或者減小時間

 

表:時間間隔表達式和單位參數

unit 值

預期expr格式

MICROSECOND

MICROSECONDS

SECOND

SECONDS

MINUTE

MINUTES

HOUR

HOURS

DAY

DAYS

WEEK

WEEKS

MONTH

MONTHS

QUARTER

QUARTERS

YEAR

YEARS

SECOND_MICROSECOND

'SECONDS.MICROSECONDS'

MINUTE_MICROSECOND

'MINUTES:SECONDS.MICROSECONDS'

MINUTE_SECOND

'MINUTES:SECONDS'

HOUR_MICROSECOND

'HOURS:MINUTES:SECONDS.MICROSECONDS'

HOUR_SECOND

'HOURS:MINUTES:SECONDS'

HOUR_MINUTE

'HOURS:MINUTES'

DAY_MICROSECOND

'DAYS HOURS:MINUTES:SECONDS.MICROSECONDS'

DAY_SECOND

'DAYS HOURS:MINUTES:SECONDS'

DAY_MINUTE

'DAYS HOURS:MINUTES'

DAY_HOUR

'DAYS HOURS'

YEAR_MONTH

'YEARS-MONTHS'

 

mysql> SELECT DATE_ADD('2018-05-01',INTERVAL 1 DAY);

     -> '2018-05-02'

mysql> SELECT DATE_SUB('2018-05-01',INTERVAL 1 YEAR);

     -> '2017-05-01'

mysql> SELECT DATE_ADD('2020-12-31 23:59:59',INTERVAL 1 SECOND);

     -> '2021-01-01 00:00:00'

mysql> SELECT DATE_ADD('2018-12-31 23:59:59',INTERVAL 1 DAY);

     -> '2019-01-01 23:59:59'

mysql> SELECT DATE_ADD('2100-12-31 23:59:59',INTERVAL '1:1' MINUTE_SECOND);

     -> '2101-01-01 00:01:00'

mysql> SELECT DATE_SUB('2025-01-01 00:00:00',INTERVAL '1 1:1:1' DAY_SECOND);

     -> '2024-12-30 22:58:59'

mysql> SELECT DATE_ADD('1900-01-01 00:00:00',INTERVAL '-1 10' DAY_HOUR);

     -> '1899-12-30 14:00:00'

mysql> SELECT DATE_SUB('1998-01-02', INTERVAL 31 DAY);

     -> '1997-12-02'

mysql> SELECT DATE_ADD('1992-12-31 23:59:59.000002',INTERVAL '1.999999' SECOND_MICROSECOND);

     -> '1993-01-01 00:00:01.000001'

 

  • DATE_FORMAT(date,format)

         將date日期時間轉換成format格式

說明符

描述

%a

工做日的縮寫名稱(Sun.. Sat)

%b

月份縮寫名稱(Jan.. Dec)

%c

月份,數字(0.. 12)

%D

英語後綴月的一天(0th, 1st,2nd, 3rd,...)

%d

每個月的某天,數字(00.. 31)

%e

每個月的某天,數字(0.. 31)

%f

微秒(000000.. 999999)

%H

小時(00.. 23)

%h

小時(01.. 12)

%I

小時(01.. 12)

%i

分鐘,數字(00.. 59)

%j

一年中的一天(001.. 366)

%k

小時(0.. 23)

%l

小時(1.. 12)

%M

月名(January.. December)

%m

月份,數字(00.. 12)

%p

AM 要麼 PM

%r

時間12小時(hh:mm:ss後跟 AM或PM)

%S

秒(00.. 59)

%s

秒(00.. 59)

%T

時間24小時(hh:mm:ss)

%U

周(00.. 53),其中星期日是一週的第一天; WEEK()模式0

%u

周(00.. 53),其中星期一是一週的第一天; WEEK()模式1

%V

周(01.. 53),其中星期日是一週的第一天; WEEK()模式2; 用於 %X

%v

周(01.. 53),其中星期一是一週的第一天; WEEK()模式3; 用於 %x

%W

工做日名稱(Sunday.. Saturday)

%w

星期幾(0=星期天.. 6=星期六)

%X

星期的年份,其中星期日是一週的第一天,數字,四位數;用於%V

%x

一週的年份,其中星期一是一週的第一天,數字,四位數;用於%v

%Y

年,數字,四位數

%y

年,數字(兩位數字)

%%

文字%字符

%x

x,對於上面未列出的任何 「 x」

 

mysql> SELECT DATE_FORMAT('2009-10-04 22:23:00', '%W %M %Y');

     -> 'Sunday October 2009'

mysql> SELECT DATE_FORMAT('2007-10-04 22:23:00', '%H:%i:%s');

     -> '22:23:00'

mysql> SELECT DATE_FORMAT('1900-10-04 22:23:00',

    ->                 '%D %y %a %d %m %b %j');

     -> '4th 00 Thu 04 10 Oct 277'

mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00',

    ->                 '%H %k %I %r %T %S %w');

     -> '22 22 10 10:23:00 PM 22:23:00 00 6'

mysql> SELECT DATE_FORMAT('1999-01-01', '%X %V');

     -> '1998 52'

mysql> SELECT DATE_FORMAT('2006-06-00', '%d');

     -> '00'

 

  • DAY(date), DAYOFMONTH(date)

         返回date中日期在當前月份中是第幾天

mysql> SELECT DAYOFMONTH('2007-02-03');

    -> 3

 

  • DAYNAME(date)

         返回date時間是星期幾

mysql> SELECT DAYNAME('2007-02-03');

    -> 'Saturday'

 

  • DAYOFWEEK(date)

         返回date時間是星期「幾」

mysql> SELECT DAYOFWEEK('2007-02-03');

    -> 7

 

  • DAYOFYEAR(date)

         返回date是一年中的第幾天,取值範圍在1~366

mysql> SELECT DAYOFYEAR('2007-02-03');

    -> 34

 

  • EXTRACT(unit FROM date)

         Unit單元和date_add/date_sub函數中的同樣,是獲取date日期的unit部分

mysql> SELECT EXTRACT(YEAR FROM '2009-07-02');

    -> 2009

mysql> SELECT EXTRACT(YEAR_MONTH FROM '2009-07-02 01:02:03');

    -> 200907

mysql> SELECT EXTRACT(DAY_MINUTE FROM '2009-07-02 01:02:03');

    -> 20102

mysql> SELECT EXTRACT(MICROSECOND FROM '2003-01-02 10:30:00.000123');

-> 123

 

  • UNIX_TIMESTAMP(), UNIX_TIMESTAMP(date)

         若是沒有date參數,則返回當前時間到1970-01-01 00:00:00之間的秒數,若是有date參數,則表示date到1970-01-01 00:00:00之間的秒數

mysql> SELECT UNIX_TIMESTAMP();

    -> 1447431666

mysql> SELECT UNIX_TIMESTAMP('2015-11-13 10:20:19');

    -> 1447431619

 

  • FROM_UNIXTIME(unix_timestamp), FROM_UNIXTIME(unix_timestamp,format)

         根據給定的unixtime,返回yyyy-mm-dd hh:mi:ss或者yyyymmddhhmiss格式的具體時間,或者按照format返回時間。

mysql> SELECT FROM_UNIXTIME(1447430881);

    -> '2015-11-13 10:08:01'

mysql> SELECT FROM_UNIXTIME(1447430881) + 0;

    -> 20151113100801

mysql> SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(),'%Y %D %M %h:%i:%s %x');

    -> '2015 13th November 10:08:01 2015'

 

  • LAST_DAY(date)

         返回date日期所在月份的最後一天日期

mysql> SELECT LAST_DAY('2004-02-05');

    -> '2004-02-29'

mysql> SELECT LAST_DAY('2004-01-01 01:01:01');

    -> '2004-01-31'

mysql> SELECT LAST_DAY('2003-03-32');

    -> NULL

 

  • SYSDATE()

         返回當前日期和時間,格式爲yyyy-mm-dd hh:mi:ss或者yyyymmddhhmiss和now()函數的區別在於now()返回的時間是語句執行的時間,而sysdate()返回的時間是該函數執行的時間

mysql> SELECT NOW(), SLEEP(2), NOW();
+---------------------+----------+---------------------+
| NOW() | SLEEP(2) | NOW() |
+---------------------+----------+---------------------+
| 2006-04-12 13:47:36 | 0 | 2006-04-12 13:47:36 |
+---------------------+----------+---------------------+
mysql> SELECT SYSDATE(), SLEEP(2), SYSDATE() ,now();
+---------------------+----------+---------------------+---------------------+
| SYSDATE()           | SLEEP(2) | SYSDATE()           | now()               |
+---------------------+----------+---------------------+---------------------+
| 2020-02-26 21:01:06 |        0 | 2020-02-26 21:01:08 | 2020-02-26 21:01:06 |
+---------------------+----------+---------------------+---------------------+

 

  • TIME(expr)

         返回expr日期時間中的時間部分

mysql> SELECT TIME('2003-12-31 01:02:03');

    -> '01:02:03'

mysql> SELECT TIME('2003-12-31 01:02:03.000123');

    -> '01:02:03.000123'

 

 

4、字符串函數

4.1經常使用的字符串函數

  • char_length(str)

         返回字符串的字符長度

mysql> select * from students;

+-----+-------+--------+---------+

| sid | sname | gender | dept_id |

+-----+-------+--------+---------+

|   1 | a     | 3      |       4 |

|   4 | c     | 3      |       1 |

|   5 | dd    | 2      |       2 |

|   6 | eee   | 2      |       4 |

+-----+-------+--------+---------+

4 rows in set (0.00 sec)

 

mysql> select sid,char_length(sname) from students;

+-----+--------------------+

| sid | char_length(sname) |

+-----+--------------------+

|   1 |                  1 |

|   4 |                  1 |

|   5 |                  2 |

|   6 |                  3 |

+-----+--------------------+

4 rows in set (0.00 sec)

 

  • concat(str1,str2,...)

         返回括號裏全部參數字符串鏈接在一塊兒,當其中有參數爲NULL時則返回NULL

mysql> SELECT CONCAT('My', 'S', 'QL');

    -> 'MySQL'

mysql> SELECT CONCAT('My', NULL, 'QL');

    -> NULL

mysql> SELECT CONCAT(14.3);

-> '14.3'

 

mysql> select * from students;

+-----+-------+--------+---------+

| sid | sname | gender | dept_id |

+-----+-------+--------+---------+

|   1 | a     | 3      |       4 |

|   4 | c     | 3      |       1 |

|   5 | dd    | 2      |       2 |

|   6 | eee   | 2      |       4 |

|   7 | NULL  | 3      |       1 |

+-----+-------+--------+---------+

5 rows in set (0.00 sec)

 

mysql> select concat(sid,sname) from students;##能夠看到有null值的行,只返回null。

+-------------------+

| concat(sid,sname) |

+-------------------+

| 1a                |

| 4c                |

| 5dd               |

| 6eee              |

| NULL              |

+-------------------+

5 rows in set (0.00 sec)

 

mysql> select concat ('sid:',sid,'@@','sname:',sname) from students;##中間能夠加一些分隔符

+-----------------------------------------+

| concat ('sid:',sid,'@@','sname:',sname) |

+-----------------------------------------+

| sid:1@@sname:a                          |

| sid:4@@sname:c                          |

| sid:5@@sname:dd                         |

| sid:6@@sname:eee                        |

| NULL                                    |

+-----------------------------------------+

5 rows in set (0.00 sec)

 

mysql> select concat ('sid:',sid,'@@','sname:',ifnull(sname,'')) from students;##去掉字符串中的null值嵌套ifnull函數,這裏用空串表示

+----------------------------------------------------+

| concat ('sid:',sid,'@@','sname:',ifnull(sname,'')) |

+----------------------------------------------------+

| sid:1@@sname:a                                     |

| sid:4@@sname:c                                     |

| sid:5@@sname:dd                                    |

| sid:6@@sname:eee                                   |

| sid:7@@sname:                                      |

+----------------------------------------------------+

5 rows in set (0.00 sec)

 

  • CONCAT_WS(separator,str1,str2,...)

         返回以第一個參數爲分隔符的鏈接後的一個字符串,當有參數爲NULL時則null被忽略。

mysql> select concat_ws(',','First name','Second name','Last Name');

+-------------------------------------------------------+

| concat_ws(',','First name','Second name','Last Name') |

+-------------------------------------------------------+

| First name,Second name,Last Name                      |

+-------------------------------------------------------+

1 row in set (0.00 sec)

mysql> SELECT CONCAT_WS(',','First name',NULL,'Last Name');

    -> 'First name,Last Name‘

mysql> select concat(sid,sname) from students;

+-------------------+

| concat(sid,sname) |

+-------------------+

| 1a                |

| 4c                |

| 5dd               |

| 6eee              |

| NULL              |

+-------------------+

5 rows in set (0.00 sec)

 

mysql> select concat_ws(',',sid,sname) from students;

+--------------------------+

| concat_ws(',',sid,sname) |

+--------------------------+

| 1,a                      |

| 4,c                      |

| 5,dd                     |

| 6,eee                    |

| 7                        |

+--------------------------+

5 rows in set (0.01 sec)

 

  • INSERT(str,pos,len,newstr)

         將str中從pos位置開始後的len個字符替換成newstr字符串

mysql> select insert('Quadratic',3,4,'What');

+--------------------------------+

| insert('Quadratic',3,4,'What') |

+--------------------------------+

| QuWhattic                      |

+--------------------------------+

1 row in set (0.00 sec)

 

mysql> select insert('Quadratic',-1,4,'What');

+---------------------------------+

| insert('Quadratic',-1,4,'What') |

+---------------------------------+

| Quadratic                       |

+---------------------------------+

1 row in set (0.00 sec)

 

mysql> select insert('Quadratic',3,100,'What');

+----------------------------------+

| insert('Quadratic',3,100,'What') |

+----------------------------------+

| QuWhat                           |

+----------------------------------+

1 row in set (0.00 sec)

 

  • instr(str,substr)

         返回str字符串中第一個出現substr字符串的位置。

mysql> select instr('foobarbar','bar');##在字符串fobarbar中第一次返回bar字符串的字符是第四個字符,故返回4。

+--------------------------+

| instr('foobarbar','bar') |

+--------------------------+

|                        4 |

+--------------------------+

1 row in set (0.00 sec)

 

mysql> select * from students;

+-----+-----------+--------+---------+

| sid | sname     | gender | dept_id |

+-----+-----------+--------+---------+

|   1 | foobarbar | 3      |       4 |

|   4 | c         | 3      |       1 |

|   5 | dd        | 2      |       2 |

|   6 | eee       | 2      |       4 |

|   7 | NULL      | 3      |       1 |

+-----+-----------+--------+---------+

5 rows in set (0.00 sec)

 

mysql> select instr(sname,'bar') from students;

+--------------------+

| instr(sname,'bar') |

+--------------------+

|                  4 |

|                  0 |

|                  0 |

|                  0 |

|               NULL |

+--------------------+

5 rows in set (0.00 sec)

 

  • LENGTH(str)

         返回str字符串的byte字節長度。

mysql> select length('test');

+----------------+

| length('test') |

+----------------+

|              4 |

+----------------+

1 row in set (0.00 sec)

 

mysql> select * from students;

+-----+-----------+--------+---------+

| sid | sname     | gender | dept_id |

+-----+-----------+--------+---------+

|   1 | foobarbar | 3      |       4 |

|   4 | c         | 3      |       1 |

|   5 | dd        | 2      |       2 |

|   6 | eee       | 2      |       4 |

|   7 | NULL      | 3      |       1 |

+-----+-----------+--------+---------+

5 rows in set (0.00 sec)

 

mysql> select length(sname) from students;

+---------------+

| length(sname) |

+---------------+

|             9 |

|             1 |

|             2 |

|             3 |

|          NULL |

+---------------+

5 rows in set (0.00 sec)

 

  • locate(substr,str)

         返回str字符串中第一次出現substr字符串的位置,若是沒有則返回null

mysql> SELECT LOCATE('bar', 'foobarbar');

    -> 4

mysql> SELECT LOCATE('xbar', 'foobar');

    -> 0

 

  • LOCATE(substr,str,pos)

         返回str字符串中從pos位置開始第一次出現substr字符串的位置,若是沒有則返回null

mysql> SELECT LOCATE('bar', 'foobarbar', 5);

    -> 7

 

  • LOWER(str)

         返回將str字符串中全部字符變換成小寫後的字符串,但對二進制文本無效。

mysql> select lower('QWERTYUIOP');

+---------------------+

| lower('QWERTYUIOP') |

+---------------------+

| qwertyuiop          |

+---------------------+

1 row in set (0.00 sec)

 

  • LTRIM(str)

         將str最左邊的空格去掉並返回。

mysql> select ltrim('   barbar');

+--------------------+

| ltrim('   barbar') |

+--------------------+

| barbar             |

+--------------------+

1 row in set (0.00 sec)

 

  • RTRIM(str)

         將字符串str右邊的空格去掉並返回。

mysql> SELECT RTRIM('barbar ');

    -> 'barbar‘

 

  • TRIM(str)

         將字符串str左右兩邊的空格去掉並返回。

mysql> select trim('  abcd  ');##這個trim等同於下面的嵌套命令

+------------------+

| trim('  abcd  ') |

+------------------+

| abcd             |

+------------------+

1 row in set (0.00 sec)

 

mysql> select rtrim(ltrim('  abcd  '));

+--------------------------+

| rtrim(ltrim('  abcd  ')) |

+--------------------------+

| abcd                     |

+--------------------------+

1 row in set (0.00 sec)

 

  • REPEAT(str,count)

         將str重複count並組合成字符串返回,若是count<1,則返回空串。

mysql> select repeat('mysql',3);

+-------------------+

| repeat('mysql',3) |

+-------------------+

| mysqlmysqlmysql   |

+-------------------+

1 row in set (0.00 sec)

 

  • REPLACE(str,from_str,to_str)

         將全部str字符串中匹配from_str字串的地方都替換成to_str子字符串。

mysql> select replace('www.mysql.com','w','Aa');

+-----------------------------------+

| replace('www.mysql.com','w','Aa') |

+-----------------------------------+

| AaAaAa.mysql.com                  |

+-----------------------------------+

1 row in set (0.00 sec)

 

  • SUBSTR(str,pos), SUBSTR(str FROM pos), SUBSTR(str,pos,len), SUBSTR(str FROM pos FOR len)
  • SUBSTRING(str,pos), SUBSTRING(str FROM pos), SUBSTRING(str,pos,len),SUBSTRING(str FROM pos FOR len)

         若是沒有len參數,則返回從pos位置開始的str中的子字符串;若是有len參數,則從pos位置開始返回str中長度爲len的子字符串;若是pos爲負值,則表明pos從右邊開始數。

mysql> select substring('Quadratically',5);

+------------------------------+

| substring('Quadratically',5) |

+------------------------------+

| ratically                    |

+------------------------------+

1 row in set (0.00 sec)

 

mysql> select substring('Quadratically'from 6);

+----------------------------------+

| substring('Quadratically'from 6) |

+----------------------------------+

| atically                         |

+----------------------------------+

1 row in set (0.00 sec)

 

mysql> select substring('Quadratically',5,6);

+--------------------------------+

| substring('Quadratically',5,6) |

+--------------------------------+

| ratica                         |

+--------------------------------+

1 row in set (0.00 sec)

 

mysql> select substring('Quadratically'from 5 for 3);

+----------------------------------------+

| substring('Quadratically'from 5 for 3) |

+----------------------------------------+

| rat                                    |

+----------------------------------------+

1 row in set (0.00 sec)

 

mysql> select substring('Quadratically',-5);

+-------------------------------+

| substring('Quadratically',-5) |

+-------------------------------+

| cally                         |

+-------------------------------+

1 row in set (0.00 sec)

 

mysql> select substring('Quadratically',-5,4);

+---------------------------------+

| substring('Quadratically',-5,4) |

+---------------------------------+

| call                            |

+---------------------------------+

1 row in set (0.00 sec)

實際場景:

mysql> select name,substring(name,1,instr(name,' ')),substring(name,instr(name,' ')) from teacher;

+-----------+-----------------------------------+---------------------------------+

| name      | substring(name,1,instr(name,' ')) | substring(name,instr(name,' ')) |

+-----------+-----------------------------------+---------------------------------+

| zhang san | zhang                             |  san                            |

| li si     | li                                |  si                             |

| wang wu   | wang                              |  wu                             |

+-----------+-----------------------------------+---------------------------------+

3 rows in set (0.00 sec)

 

4.2 不太經常使用的字符串函數

  • ASCII(str)

         返回str字符串中最左邊字符的ascii碼值,若是是空串則返回0,若是str是null則返回null

mysql> SELECT ASCII('2');

    -> 50

mysql> SELECT ASCII(2);

    -> 50

mysql> SELECT ASCII('dx');

    -> 100

 

  • CHAR(N,... [USING charset_name])

         將括號中的N轉化成ascii碼對應的字符,返回這些字符組成的字符串,其中的null會被忽略

mysql> SELECT CHAR(77,121,83,81,'76');

     -> 'MySQL'

mysql> SELECT CHAR(77,77.3,'77.3');

     -> 'MMM‘

mysql> SELECT CHARSET(CHAR(X'65')), CHARSET(CHAR(X'65' USING utf8));

+----------------------+---------------------------------+

| CHARSET(CHAR(X'65')) | CHARSET(CHAR(X'65' USING utf8)) |

+----------------------+---------------------------------+

| binary | utf8 |

+----------------------+---------------------------------+

 

  • LEFT(str,len)

         返回str字符串中從左邊開始的len個長度的字符

mysql> SELECT LEFT('foobarbar', 5);

    -> 'fooba‘

 

  • LOAD_FILE(file_name)

         讀取文件且返回文件內容爲字符串

mysql> UPDATE t SET blob_col=LOAD_FILE('/tmp/picture') WHERE id=1;

 

  • LPAD(str,len,padstr)

         將str的左邊補充爲padstr,直到補充成len長度的字符串並返回;若是str的長度比len長,則返回str中最左邊開始的len長度的字符

mysql> SELECT LPAD('hi',4,'??');

    -> '??hi'

mysql> SELECT LPAD('hi',1,'??');

    -> 'h'

 

  • REVERSE(str)

         將str字符串中的字符按照倒序組合並返回

mysql> SELECT REVERSE('abc');

    -> 'cba‘

 

  • RIGHT(str,len)

         將str字符串中從右邊開始的len個字符返回

mysql> SELECT RIGHT('foobarbar', 4);

    -> 'rbar'

 

  • RPAD(str,len,padstr)

         將字符串str從右邊開始補充爲padstr直到總體長度爲len,若是str的長度自己大於len,則返回str中len長度的字符串

mysql> SELECT RPAD('hi',5,'?');

    -> 'hi???'

mysql> SELECT RPAD('hi',1,'?');

    -> 'h'

 

  • RTRIM(str)

         將字符串str右邊的空格去掉並返回

mysql> SELECT RTRIM('barbar ');

    -> 'barbar'

 

  • SPACE(N)

         返回N個長度的空格組成的空字符串

mysql> SELECT SPACE(6);

    -> ' '

 

  • SUBSTRING_INDEX(str,delim,count)

         當count爲正數,則返回delim出如今str字符串中第count次以前的子字符串,若是是負數,則從右邊開始計算

mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', 2);

    -> 'www.mysql'

mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', -2);

    -> 'mysql.com‘

 

  • UPPER(str)

    返回將str字符串中全部字符轉換成大寫的字符串

mysql> SELECT UPPER('Hej');

    -> 'HEJ‘

 

 

5、字符串對比函數

name

description

like

簡單模式匹配

not like

簡單模式匹配的否認

strcmp()

比較兩個字符串

5.1 like對比函數

  • 通配符%表示匹配0個或多個字符
mysql> select * from students;

+-----+-------+--------+---------+

| sid | sname | gender | dept_id |

+-----+-------+--------+---------+

|   1 | aa    | 3      |       1 |

|   4 | cc    | 3      |       1 |

|   5 | dd    | 1      |       2 |

|   6 | aac   | 1      |       1 |

|  10 | a     | 1      |       1 |

|  20 | bac   | 1      |       1 |

+-----+-------+--------+---------+

6 rows in set (0.00 sec)

 

mysql> select * from students where sname like 'a%';##匹配以"a"開頭的0個或多個字符

+-----+-------+--------+---------+

| sid | sname | gender | dept_id |

+-----+-------+--------+---------+

|   1 | aa    | 3      |       1 |

|   6 | aac   | 1      |       1 |

|  10 | a     | 1      |       1 |

+-----+-------+--------+---------+

3 rows in set (0.00 sec)

 

mysql> select * from students where sname like '%a%';##配置字符串中有「a」的行

+-----+-------+--------+---------+

| sid | sname | gender | dept_id |

+-----+-------+--------+---------+

|   1 | aa    | 3      |       1 |

|   6 | aac   | 1      |       1 |

|  10 | a     | 1      |       1 |

|  20 | bac   | 1      |       1 |

+-----+-------+--------+---------+

4 rows in set (0.00 sec)

 

mysql> select * from students where sname like 'a%a%';##以「a」開頭其中還有一個「a」的字符串。

+-----+-------+--------+---------+

| sid | sname | gender | dept_id |

+-----+-------+--------+---------+

|   1 | aa    | 3      |       1 |

|   6 | aac   | 1      |       1 |

+-----+-------+--------+---------+

2 rows in set (0.00 sec)

 

mysql> select * from students where sname like '%a';##匹配以a結尾的字符串

+-----+-------+--------+---------+

| sid | sname | gender | dept_id |

+-----+-------+--------+---------+

|   1 | aa    | 3      |       1 |

|  10 | a     | 1      |       1 |

+-----+-------+--------+---------+

2 rows in set (0.00 sec)

 

mysql> select * from students where sname like 'a%c';##匹配以「a」開頭以「c」結尾的字符串

+-----+-------+--------+---------+

| sid | sname | gender | dept_id |

+-----+-------+--------+---------+

|   6 | aac   | 1      |       1 |

+-----+-------+--------+---------+

1 row in set (0.00 sec)

 

  • 通配符「_」表示匹配1個字符
mysql> select * from students;

+-----+-------+--------+---------+

| sid | sname | gender | dept_id |

+-----+-------+--------+---------+

|   1 | aa    | 3      |       1 |

|   4 | cc    | 3      |       1 |

|   5 | dd    | 1      |       2 |

|   6 | aac   | 1      |       1 |

|  10 | a     | 1      |       1 |

|  20 | bac   | 1      |       1 |

+-----+-------+--------+---------+

6 rows in set (0.00 sec)

 

mysql> select * from students where sname like 'a_';##以「a」開頭,後面的字符必須是一個字符。

+-----+-------+--------+---------+

| sid | sname | gender | dept_id |

+-----+-------+--------+---------+

|   1 | aa    | 3      |       1 |

+-----+-------+--------+---------+

1 row in set (0.00 sec)

 

mysql> select * from students where sname like 'a_%';##表示以「a」開頭,後面必須有一個字符,而後後面能夠匹配0到多個任意字符

+-----+-------+--------+---------+

| sid | sname | gender | dept_id |

+-----+-------+--------+---------+

|   1 | aa    | 3      |       1 |

|   6 | aac   | 1      |       1 |

+-----+-------+--------+---------+

2 rows in set (0.00 sec)

 

  • 當匹配字符中有特殊字符時,能夠用 \或者escape來指定特殊字符爲字符
mysql> select * from students;

+-----+-------+--------+---------+

| sid | sname | gender | dept_id |

+-----+-------+--------+---------+

|   1 | aa    | 3      |       1 |

|   4 | cc    | 3      |       1 |

|   5 | dd    | 1      |       2 |

|   6 | aac   | 1      |       1 |

|  10 | a     | 1      |       1 |

|  20 | bac   | 1      |       1 |

+-----+-------+--------+---------+

6 rows in set (0.00 sec)

 

mysql> select * from students where sname like 'a\%';##該命令至關與where sname='a%',百分號再也不表示匹配0或多個字符,而是一個字符。

Empty set (0.00 sec)

 

5.2 not like對比函數

       是上一個字符串對比函數的反義

expr NOT LIKE pat [ESCAPE 'escape_char']

 

5.3 strcmp(expr1,expr2)對比函數

       當expr1等於expr2時等於0,當expr1小於expr2時爲-1,反之爲1

mysql> SELECT STRCMP('text', 'text2');

    -> -1

mysql> SELECT STRCMP('text2', 'text');

    -> 1

mysql> SELECT STRCMP('text', 'text');

    -> 0

 

 

6、格式轉換函數

Cast()和convert()

       兩個函數均可以用來轉換數據類型或者轉換字符集

容許轉換的數據類型包括:

       Binary[N]

       char[N]

       Date

       Datetime

       decimal[M,[D]]

       Time

       Signed [integer]

       Unsigned [integer]

SELECT CONVERT(_latin1'Müller' USING utf8);

SELECT CONVERT('test', CHAR CHARACTER SET utf8);

SELECT CAST('test' AS CHAR CHARACTER SET utf8);

select CAST('2000-01-01' AS DATE);

select CONVERT('2000-01-01', DATE);

 

 

7、聚合函數

  • 用在存在group by子句的語句中

 

  • AVG([DISTINCT] expr)

         計算expr的平均值,distinct關鍵詞表示是否排除重複值

mysql> SELECT student_name, AVG(test_score) FROM student GROUP BY student_name;

 

  • COUNT(expr)

         計算expr中的個數,若是沒有匹配則返回0,注意NULL的區別

mysql> SELECT student.student_name,COUNT(*) FROM student,course WHERE student.student_id=course.student_id GROUP BY student_name;

 

  • COUNT(DISTINCT expr,[expr...])

         計算有多少個不重複的expr值,注意是計算非NULL的個數

mysql> SELECT COUNT(DISTINCT results) FROM student;

 

  • MAX([DISTINCT] expr),MIN([DISTINCT] expr)

         返回expr中最大或者最小的值

mysql> SELECT student_name, MIN(test_score), MAX(test_score) FROM student GROUP BY student_name;

 

  • SUM([DISTINCT] expr)

         返回expr的求和值

 

 

8、

相關文章
相關標籤/搜索