選出表中字符的長度: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):如果expr1為null,則返回expr2,否則返回expr1 -
nullif(expr1,expr2):如果expr1和expr2相等,則返回null,否則返回expr1. -
if(expr1,expe2,expr3):有點(diǎn)類似于?:三元運(yùn)算符,如果expr1為true,不等于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;