mysql语句中有很多内置的函数,熟练的掌握这些函数可以让我们在工作是事半功倍,有助于了解mysql语句的精髓。下面简单介绍几种常见的函数。
字符串函数
数字函数
日期函数
高级函数
1、字符串函数
1、ascII(s)
返回字符串的第一个字符的ASCII码
select ascii(columns) as col1 from table_name;
2、char_length(s)
返回字符串的字符数
select char_length(columns) as col2;
3、concat(a1,a2,a3,...)
将字符串a1,a2,等多个字符串合并成为一个字符串
select concat('a1','a2','a3') as tb3;
4、concat_ws(x,a1,a2,...)
将字符串合并成一个字符串,但是字符串之间加上'x'
select concat_ws('x','a1','a2')as tb4;
5、field(a,a1,a2,a3)
返回第一个字符串在字符串列表(a1,a2,a3)中的位置
select field('a','b','a','c','d')as tb5;
6、format(x,n)
将数字x进行格式化,将x保留到小数点后n位,最后一位四舍五入
select format(23.90,1);
7、insert(a1,x,len,a2)
将字符串a2替换a1的X位置开始的长度为len的字符串
select insert('abcd.xom',1,4,'dewa');
8、left(a,n)
返回字符串a的前n个字符
select left('abcdef',2);
9、ltrim(s)
去除字符串s开始处的空格
select ltrim(' abcs');
10、mid(s,n,len)
从字符串s的n位置截取长度为len的子字符串,
select min('abaass',2,3);
11、replace(a,a1,a2)
将字符串a2代替字符串a中的字符串a1
select replace('abc','a','x')
12、right(s,n)
返回字符串s的后n个字符
select right('abdcs',2)
13、substr(s,start,len)
从字符串s的start位置截取长度为len的子字符串
select substr('abdxc',2,3)
2、数字函数
1、abs(x)
返回X的绝对值
select abs(-1)
2、avg(exp)
返回一个表达式的平均值
select avg(exp);
3、count(exp)
返回查询记录总数
select count(exp);
4、exp(x)
返回e的x次方
select exp(x);
5、max(exp)
返回字段exp中的最大值
select max(exp);
6、min(exp)
返回字段exp中的最小值
select min(exp);
7、mod(x,y)
返回x除以y以后得余数
select mod(3,2);
8、sum(exp)
返回指定字段的总和
select sum(exp);
3、时间函数
1、getdate()
查找当前的时间
select getdate()
2、dateadd(a,2,date)
dateadd在向指定日期加上一段时间的基础上,返回新的datetime值
select dateadd(day,2 or -2,getdate())
3、datediff(day,date1,date2)
datediff返回跨两个指定日期的日期和时间天数
select datediff(day,时间1,时间2)
4、datepart(a,date)
datepart返回代表指定日期的指定日期部分的整数
select datepart(month,'2019-10-10')
5、datename(x,date)
datename返回代表指定日期的指定日期部分的字符串
select datename(weekday,'2019-10-10')
6、day()、month()、year()
day(),month(),year()返回的是指定日期的年、月、日
select day(getdate())
select month(getdate())
select year(getdate())
7、convert()
日期格式的转换(convert)常见的转换形式有:
select convert(varchar(100),getdate(),120) --2019-05-16 10:57:47
select convert(varchar(100),getdate(),23) --2019-05-16
select convert(varchar(100),getdate(),102) --2019.05.16
select convert(varchar(100),getdate(),111) --2019/05/16
select convert(varchar(100),getdate(),112) --20190516
8、now()
返回当前日期和时间
select now()
9、date()
从日期或日期时间表达式中提取日期值
select date('time')
10、date_format(d,f)
按照表达式f的要求显示日期d
select date_format('2019-01-01','%Y-%m-%d')
4、高级函数
1、case exp
when condition1 then res1
when condition2 then res2
else res3
end
case表示函数开始,end表示函数结束,如果condition1成立,返回res1,condition2成立,返回res2,否则返回res3
select case
when 1>0 then 'a'
when 2>1 then 'b'
else 'c'
end
2、cast(x as type)
转换数据类型
select cast('2019-01' as char);
3、if(expr,a1,a3)
如果表达式expr成立,返回结果a1,否则返回a2
select if (1>0 ,'1','0')
4、ifnull(a1,a2)
如果a1的值不为null,则返回a1,否则返回a2
select ifnull(null,'abc')
随着大数据的时代的到来,数据变得越来越重要,数据可以帮助我们来看清行业的本质,也可以帮助我们更加快速的了解一个行业,关注公众号——有趣的数据,走进数据的时代。