數據庫(DataBase)-常用函數

MySQL函數

官網:https://dev.mysql.com/doc/refman/5.7/en/func-op-summary-ref.html

1.常用函數

(1)數學運算

-- 絕對值
select abs(-77); -- 77

-- 向上取整
select ceiling(77.77); -- 78

-- 向下取整
select floor(77.77); -- 77

-- 返回一個0-1的隨機數
select rand(); -- 每次都不一樣

-- 判斷一個數的符號,0返回0,正數返回1,負數返回-1
select sign(0);
select sign(7);
select sign(-77);

(2)字符串函數

-- 返回字符串長度,空格(Space)也包括在內。
select char_length('Alita Battle Angle');

-- 合併字符串,注意是否需要空格。
select concat('I',' ','Love',' ','you',' ','my',' ','dear',' ','Alita');

-- 插入,在指定位置開始替換指定字符串
select insert('我愛編程,我愛Java',1,2,'超級無敵');

-- 轉換大小寫
select lower('EDWIN JARVIS');

select upper('edwin jarvis');

-- 查找首次出現的位置
select instr('Edwin Jarvis','e');

-- 替換出現的指定字符串
select replace('Edwin Jarvis said keep going on and you will succeed.',
				'and you will succeed.','and you will make it!');

-- 返回指定的子字符串,格式:(源字符串,起始位置,結束位置);
select substr('Edwin Jarvis said keep going on and you will succeed.',7,17);

-- 翻轉字符串
select reverse('Edwin Jarvis said keep going on and you will succeed.');

use school;
-- 混合應用,查詢姓“成”的同學,將其姓氏改爲“陳”
select replace(name,'成','陳') from student
where name like '成%';

(3)時間和日期函數(重要,記憶)

-- 獲取當前日期
select current_date();-- '2020-05-15'

select curdate();

-- 獲取當前日期和時間
select now(); -- 2020-05-15 10:46:05

-- 獲取本地時間
select localtime(); -- '2020-05-15 10:46:50'

-- 獲取系統時間
select sysdate(); -- '2020-05-15 10:47:37'

-- 年月日時分秒
select year(now());-- 2020
select month(now());-- 5
select day(now());-- 15
select hour(now());-- '10'
select minute(now());-- '48'
select second(now());-- '48'

(4)系統函數

select System_user(); -- root@localhost

select user(); -- root@localhost

select version(); -- 5.5.36

2.聚合函數(常用)

函數名稱 功能描述
count() 計數
sum() 求和
avg() 求平均
max() 求最大值
min() 求最小值

1.count()函數

count():想要查詢表中有多少數據時使用的函數。

count(指定列),查詢指定列一共有多少條數據,會忽略null值,本質:計算name行數。

-- ================== 聚合函數 ====================
select count(name) from student;

-- count(*),查詢本表格一共有多少條數據,不會忽略null值,本質:計算行數。
-- 大數據情況下,不推薦,運行時間可能會很長。
select count(*) from student;

-- count(列序號),不會忽略null值,本質:計算行數。
select count(1) from student;

執行效果上:

count(*)包括了所有的列,相當於行數,在統計結果的時候,不會忽略列值爲NULL

count(1)包括了忽略所有列,用1代表代碼行,在統計結果的時候,不會忽略列值爲NULL

count(列名)只包括列名那一列,在統計結果的時候,會忽略列值爲空(這裏的空不是隻空字符串或者0,
而是表示null)的計數,即某個字段值爲NULL時,不統計。

執行效率上:

列名爲主鍵,count(列名)會比count(1)快

列名不爲主鍵,count(1)會比count(列名)快

如果表多個列並且沒有主鍵,則 count(1) 的執行效率優於 count( * )

如果有主鍵,則 select count(主鍵)的執行效率是最優的

如果表只有一個字段,則 select count(*)最優。

2.求和函數

select sum(`StudentResult`) as 總分 from student;
select avg(`StudentResult`) as 均分 from student;
select max(`StudentResult`) as 最高分 from student;
select min(`StudentResult`) as 最低分 from student;

參考文獻

《【狂神說Java】MySQL最新教程通俗易懂》
視頻連接:https://www.bilibili.com/video/BV1NJ411J79W

2020.05.24

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章