MySQL數(shù)據(jù)庫常用函數(shù)

選出表中字符的長度:char_length

select char_length(name) from customer;

計算那么列字符串長度的sin值

select sin(char_length(name)) from customer;

計算1.57的sin值

select sin(1.57)

為指定的日期添加一定的時間

這種用法下interval是關(guān)鍵字,需要一個數(shù)值,還需要一個單位

select DATE_ADD('2017-08-16', interval 2 MONTH);

這種方法更簡單

select ADDDATE('2017-08-16',2);

獲取當(dāng)前日期

select CURDATE();

獲取當(dāng)前時間

select curtime();

獲取MD5的加密函數(shù)

select MD5('testing')

MySQL還提供了幾個處理null的函數(shù)

  • ifnull(expr1,expr2):如果expr1null,則返回expr2,否則返回expr1
  • nullif(expr1,expr2):如果expr1expr2相等,則返回null,否則返回expr1.
  • if(expr1,expe2,expr3):有點(diǎn)類似于?:三元運(yùn)算符,如果expr1true,不等于0,且不等于null,則返回expr2,否則返回expr3。
  • isnull(expr1):判斷expr1是否為null,如果為null則返回true,否則返回false
例如:
#如果name列為null,則返回‘沒有名字’
select ifnull(name,'沒有名字') from customer;

#如果name列等于‘張三’,則返回null
select nullif(name,'張三') from customer;

#如果name列為null,則返回”沒有名字“,否則返回”有名字“
select if(isnull(name),'沒有名字','有名字') from customer;

MySQL還提供了一個case函數(shù),該函數(shù)是一個流程控制函數(shù)。case函數(shù)有兩個用法.

1.case函數(shù)的第一個用法的語法格式如下:
case value
when compare_value1 then result1
when compare_value2 then result2
...
else reuslt
end

case函數(shù)用value和后邊的compare_value1、compare_value2、...依次進(jìn)行比較,如果value和指定的compare_value1相等,則返回對應(yīng)的result,否則返回else后的result。例如如下SQL語句:

# 如果teacher為1,則返回“李老師”,為2則返回“張老師”,否則返回“其他老師”
select student_name, case teacher 
when 1 then '李老師' 
when 2 then '張老師' 
else '其他老師' 
end 
from student_table;
2.case的第二個用法的語法格式如下:
case
when condition1 then result1
when condition2 then result2
...
else result
end

在第二個用法中,condition1,、condition2都是一個返回boolean值得條件表達(dá)式,因此這種用法更加靈活。例如如下SQL語句:

# id 小于3的為初級班,3--6的為中級班,其它的為高級班
select student_name, case
when student_id<3 then '初級班' 
when student_id<=6 then '中級班' 
else '高級班' 
end 
from student_table;

分組和組函數(shù)

  • avg([distinct|all]expr):計算多行expr的平均值,expr可以是變量、常量或數(shù)據(jù)列,但是其數(shù)據(jù)類型必須是數(shù)值型。distinct表示計算值不能為重復(fù)值。
  • count({*|[distinct|all]expr}):計算多行expr的總條數(shù),其中expr可以是變量、常量或者數(shù)據(jù)列,其數(shù)據(jù)類型可以是任意值類型;(*)表示統(tǒng)計該表中的記錄行數(shù);distinct表示不計算重復(fù)值。
  • max(expr):計算多行expr的最大值,其中expr可以是變量、常量或者數(shù)據(jù)列,其數(shù)據(jù)類型可以是任意值類型;
  • min(expr):計算多行expr的最小值,其中expr可以是變量、常量或者數(shù)據(jù)列,其數(shù)據(jù)類型可以是任意值類型;
  • sum([distinct|all]expr):計算多行expr的總和。其中expr可以是變量、常量或者數(shù)據(jù)列,但其數(shù)據(jù)類型必須為數(shù)值類型;distinct表示不計算重復(fù)值。

對于可能出現(xiàn)null的列,可以使用ifnull函數(shù)來處理該列。

# 計算expr列所有列的平均值
select avg(ifnull(expr, 0)) from table;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容