MySQL函式
前言
這一小節學習的是MySQL的函式,與其他語言的函式操作很相像,也比較簡單,學習一些常用的掌握即可!
MySQL函式官網:MySQL函式大全
1、常用函式
Java能用的MySQL基本都能用
--數學運算
select abs(-100) --abs絕對值函式
select ceiling(3.9) --ceiling向上取整函式
select floor(3.9) --floor向下取整函式
select rand() --rand回傳一個0~1之間的亂數
select sign(39) --判斷一個數的符號 0回傳0 負數回傳-1 正數回傳1
--字串
select char_length('123456') --回傳字串長度
select concat('MySQL','和','Java') --合并字串
select insert('我愛編程',1,2,'超級熱愛') --查詢,從某一個位置開始替換某個長度(從第1位置替換2個長度) 回傳:超級熱愛編程
select lower('woodwhale') --小寫字母
select upper('woodwhale') --大寫字母
select instr('woodwhale','w') --回傳第一次出現的子串的索引
select replace('新年快樂','新年','牛年') --替換出現的指定字串
select substr('新年快樂萬事如意',1,4) --回傳指定的子字串,使用方法:字串,截取開始位置,截取字符長度, 例子的回傳值:新年快樂
select reverse('樂快年新') --反轉,例子回傳值:新年快樂
--查詢姓周的同學,將 姓氏 周 改為 吳
select replace(studentname,'周','吳') from student
where studentname like '周%'
--時間和日期函式
select current_date() --獲取當前日期
select curdate() --和current_date一樣
select now() --獲取當前時間
select localtime() --獲取當地時間
select sysdate() --獲取系統時間
select year(now()) --獲取某個時間的年份,day,month,hour,second,minute同理
--系統
select system_user()
select user()
select version()
2、聚合函式
聚合函式用的比較多,需要掌握!
| 函式名稱 | 描述 |
|---|---|
| count() | 計數 |
| sum() | 求和 |
| avg() | 平均值 |
| max() | 最大值 |
| min() | 最小值 |
| … | … |
--查詢表中有多少個記錄用count()
select count(studentname) from student -- count(指定列)
select count(*) from student -- count(*)
select count(1) from student --count(1)
區別:
count(指定列):會忽略所有的null值
count(*):不會忽略null值,計算行數,計算所有列
count(1):不會忽略null值,計算行數,計算一列的行
具體的細小差別可以查閱其他博客進行深究~
--sum() avg() max() min()
select sum(studnetresult) as 總分 from result
select avg(studnetresult) as 平均分 from result
select max(studentresult) as 最高分 from result
select min(studentresult) as 最低分 from result
聚合函式的練習:
--查詢不同課程的平均分,最高分,最低分,平均分大于80
select subjectname,avg(studentresult) as 平均分,max(studentresult) as 最高分,min(studentresult) as 最低分
from result as r
inner join `subject` as sub
on r.subjectno = sub.subjectno
group by r.subjectno --通過(學科編號)來分組
having 平均分>80 --次要條件過濾用having
后話
MySQL函式這一章節的知識還是很簡單的,小伙伴們熟練地掌握使用就可以啦!
如果有任何疑問或錯誤,可以在評論區指出,咱們一起探討!
ps:我的上一篇MySQL學習博客:MySQL學習之《查詢資料》,有興趣的小伙伴可以參考噢!
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/259802.html
標籤:其他
