MySQL基礎之常用函數

數學函數的使用

常用數學函數

函數 作用 函數 作用
ceil() 進一取整 abs() 取絕對值
floor() 舍掉小數部分 power() 冪運算
round() 四捨五入 pi() 圓周率
truncate() 截取小數點後幾位 rand()或者rand(x) 0~1之間的隨機數
mod 取餘數 sign(x) 得到數字符號
exp() 計算e的x次方

用法

select ceil(1.2);
select floor(2.9);
select round(3.56789,2);
select truncate(3.456789,3);
select 10 mod 3;
select id,username,ceil(salary) from user;

字符串常用函數

--char_length():得到字符串的字符數
select char_length('abc');

--length():得到字符串的長度(一箇中文字符在utf8下佔3個長度)
select length('abc');

--concat(s1,s2,...):將字符串合併成一個字符串(參數裏有null最終結果爲null)
select concat('a','b','c');

--concat_ws():以指定分隔符拼接字符串
select concat_ws('-','a','b','c',null); --null不起作用
select concat_ws(null,'a','b','c'); --以null作爲分隔符結果爲null

--upper()|ucase()|lower()|lcase():將字符串轉換成大寫或者小寫
select upper('hello world'),ucase('hello world'),lower('HELLO WORLD'),lcase('HELLO WORLD');

--reverse():字符串的反轉
select reverse('abc');

--left()|right():返回字符串的前幾個字符或者後幾個字符
select left('hello',2),right('hello',2);

--lpad()|rpad():用字符串填充到指定長度
select lpad('abc',10,'?'); --從'abc'左端用'?'填充到10位

--trim()|ltrim()|rtrim():去掉字符串兩端的空格
select concat('*',trim(' abc '),'*');

--repeat():重複指定的次數
select repeat('hello',3);

--replace():替換指定的字符串
select replace('hello king','king','queen'); --將'king'替換成'queen'

--substring():截取字符串
select substring('abcdef',1,3); --從1開始截取3位,abc

--strcmp():比較字符串
select strcmp('a','b');

日期時間常用函數的使用

--返回當前日期
select curdate(),current_date();

--返回當前時間
select curtime(),current_time();

--返回當前的日期時間
select now(),current_timestamp(),sysdate();

--返回日期中的月份和月份的名稱
select month('2017-02-19');
select month(current_date()),monthname(curdate());

--返回星期幾
select dayname(now());

--返回一週內的第幾天(1:星期天,2:星期一,...)
select dayofweek(now());

--返回一年中的第幾個星期
select week(now());

--返回日期中的年份、月份、天、小時、分鐘
select year(now()),month(now()),day(now()),hour(now()),minute(now()),second(now());

--計算兩個日期相差的天數
select datediff('2017-03-05','2017-03-01');

其他常用函數

--得到MySQL版本、當前服務器的連接數
select version(),connection_id();

--得到當前的數據庫名
select database(),schema();

--得到當前登陸的用戶
select user(),current_user(),system_user(),session_user();

--得到上一步插入操作產生auto_increment的值
select last_insert_id();

--加密
select md5('king');

--密碼加密算法
select password('root');
發佈了23 篇原創文章 · 獲贊 22 · 訪問量 3423
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章