MySql常用函式介紹

2021-08-20 12:06:31 字數 3145 閱讀 4525

1.ifnull用法

eg:

ifnull

(b.member_count, 0)

member_count

2.if用法

格式:if(value,exp1,exp2),

描述:如果value == true , 執行exp1 ;value == false ,則執行exp2。

eg:

if (

length(trim(b.group_name)) > 0,

b.group_name,

group_concat(

if (

length(trim(e.user_name)) > 2,

right (e.user_name, 2),

e.user_name

) separator '+'

)) session_user_name

3.contact函式

作用:將多個字串連線。

格式:contact(str1,str2,…)

注意:若其中乙個字串為null,則返回值是null

eg:

//info欄位不存在分隔符

select

concat (id, name, score) as info from student

//info欄位「,」分隔符

select

concat (id, 『,』,name, 『,』,score) as info from student

4.contact_ws()函式

作用:將多個字串連線,並且制定分隔符

格式:contact_ws(separator,str1,str2)

eg:

//info欄位「,」分隔符

select concat_ws (『,』,id, name, score) as info from student

5.group by函式

作用:按照字段進行分組

格式:group by 字段

eg:

在學生表中查詢相同name中最小id:

select name,min(id) from student group

by name;

注意,如果是查詢學生表中相同名字所有id:

select name,id from student order

by name;

6.group_contact()函式

作用:將group by 產生的同乙個分組中的值連線起來,返回乙個字串結果。

格式:group_contact([distinct] 要連線的字段 [order by 排序字段 asc/desc] [separator 『分隔符』])

注意: distinct 去重,order by 排序 ,separator 分隔符 ,分隔符預設是「,」

eg:

使用group_contact()和group by 顯示相同名字的人的id:

select name ,group_contact(id) from student group

by name;

結果:

小麗 3

小明 1,5,6

小王 2,4

將上面的id號從大到小排序,分隔符「_」:

select name,group_contact(id order

by id desc separator 『_』) from student group

by name;

結果:

id desc separator 『_』)

小麗 3

小明 6_5_1

小王 4_2

查詢以name分組的所有組的id和score:

select name ,group_contact(contact_ws(「,」,id,score) order

by id ) from student group

by name;

結果:

id )

小麗 3-0

小明 1-0,5-0,6-0

小王 2-0,4-0

7.length()函式

作用:統計字串長度,單位:位元組。

格式:length(str)

eg:

select length("text");
結果:

4
8.trim()函式

功能:裁剪字串空白處。

格式:trim(字串)

注意:ltrim(字串): 將所有字串起頭的空白移除。

rtrim(字串): 將所有字串結尾的空白移除。

eg:

select

trim(' sample ');

select

ltrim(' sample ');

select

rtrim(' sample ');

結果:

'sample'

'sample '

' sample'

9.left(),right()函式

功能:left、right函式返回的是傳入引數最左邊、右邊的長度為length個的字串。

格式:left(引數,length)、right(引數,length)

eg:

select

left('abcdefg',3) from a;

結果:

left('abcdefg',3)

abc

10.alert table 增加列,修改列

alter table tax_link add columnpage_idint(32) default null comment 『頁面id』

MySql中常用轉換函式介紹

cast函式 convert函式 用法 cast expr as type convert expr,type convert expr using transcoding name select convert abc using utf8 將varchar 轉為int 用 cast str as...

mysql 常用函式迴圈 mysql 常用函式

mysql 常用函式 數字函式 ceiling x 返回大於x的最小整數值 floor x 返回小於x的最大整數值 truncate x,y 返回數字x截短為y位小數的結果 僅僅只是截斷,不會進行四捨五入計算 聚合函式 group concat col 返回由屬於一組的列值連線組合而成的結果 字串函...

mysql常用函式哪些 MySQL常用函式彙總

數學類函式 ceil x ceilin x 進一取整 floor x 捨掉小數部分 round x,y 四捨五入 保留y位小數 mod x,y x除以y以後的餘數 abs x 取x的絕對值 power x,y pow x,y 冪運算 x的y次冪 pi 圓周率 rand 或者rand x 0 1之間的...