MySQL學習系列二 MySQL函式

2021-07-30 14:44:18 字數 2995 閱讀 1313

mysql提供了一些操作字串和日期等的內建函式,可以大大簡化我們的開發,這裡整理一下常用的函式。

字串函式

bin(number)

返回給定整數值對應的二進位制字串,輸入null則返回null。

select bin(10) ----> 1010
cast(experssion as type)

將一種資料型別轉為另一種資料型別的值。type可以是char、date、datetime、time、binary等。

coalesce(column[,…])

返回逗號分隔符列表中最左邊的非null的字串或列,如所有都為null則返回null。

//fristname有值,則返回firstname,都沒有返回「noname」

select coalesce(firstname,secondname,「noname」)

concat(string,…)

將字串或列拼接起來,合併到乙個欄位中,如果有乙個為null,則返回null。還可以將給定列的數值轉為字串。

select concat(firstname,' ',secondname) as name form user

concat_ws(separator,stirng,..)

用指定的分隔符連線列或字串。

select concat_ws('|','a','b','c') ---> a|b|c
find_in_set(string,string_list)

返回第乙個引數在第二個引數的位置,第二個引數時由逗號隔開的單一字串,沒有則返回0,有乙個為null,則返回null。

select find_in_set('b','a,b,c') ----> 2
insert(string,position,length,new_string)

將最後乙個引數插入到第乙個引數的指定位置,如果length大於0,會覆蓋指定數目的字元,即替換,如果乙個引數為null,則返回null。

select

insert('123456',2,0,'7') ----> 1723456

select

insert('123456',2,1,'7') ----->173456

select

insert('123456',2,2,'7') ----->17456

instr(string,substring)

返回子字串在第乙個引數首次出現的位置。沒有返回0。

lower(string)

轉換為小寫字母。

left(string,length)

返回左邊的length長個字元。

select left('123456',3) ----->123
length(stirng)

返回字串的長度,假定乙個字元為乙個位元組

load_file(file)

讀取檔案內容,作為字串返回。

select load_file('d:\1.txt')
locate(substring,string,postion)

返回子字串在string首次出現的位置,position收索的位置。

mid(string,position,length)

擷取字串。

replace(string,old,new)

字串替換。

reverse(string)

倒序。日期和時間函式

adddate(date,days)

adddate(date,interval value type)

為指定日期加乙個時間間隔。

select adddate('2017-04-15',interval

1month) -----> 2017-05-15

curdate()

以yyyy-mm-dd返回當前時間。

curtime()

以hh:mm:ss返回當前時間

date(experssion)

返回yyyy-mm-dd部分。

date_format(date,」)

格式化日期。

datediff(date,date)

返回兩個日期的差值(天數)。

select datediff('2017-03-15','2017-04-15') ---> -31
day(date)

返回日期在某月的天數

last_day(date)

返回date月的最後一天的日期。

month(date)

返回月份。

second(date)

返回秒數

yerr(date)

返回年份

控制流程函式

case value when value1 then result … else end

case when conditionthen result … else end

if(condition,result1,result2)

如果condition值為0或null,返回result2,否則返回result1

ifnull(condition,result)

如果condition不為null,則返回condition的值,否則返回result

isnull(column)

如果為null返回1,不為null返回0

nullif(condition,condition2)

如果兩個引數相等,返回null,否則返回第乙個引數的結果

MySql系列 (二) MySql索引

索引可以理解為字典的音序表一樣,可以根據它來查詢匹配的資料項。實際上索引是一種對資料表的一列或多列字段進行排序的資料結構,常見的索引資料結構就是b 樹 什麼是b 樹?索引主要是啟提高資料查詢的效率,幫助我們快速的在大量資料中定位到我們要找的資料。簡單的例子 下面這張表有4個字段,主鍵id 會員id ...

MySQL學習系列一

看了 mysql核心技術手冊 在這裡整理一下知識點。安全 使用者語句和函式 使用者的訪問許可權可以是全域性層級 伺服器上的所有資料庫 也可以是資料庫層級 表層級和列層級。使用者的許可權儲存在授權表中,位於伺服器的mysql資料庫中 user 全域性級許可權 db 資料庫層級許可權 tables pr...

MySql學習系列(四)

專案十 行程和使用者 難度 困難 trips 表中存所有計程車的行程資訊。每段行程有唯一鍵 id,client id 和 driver id 是 users 表中 users id 的外來鍵。status 是列舉型別,列舉成員為 completed cancelled by driver cance...