数据库函数

数学函数
abs(x) 返回x的绝对值
bin(x) 返回x的二进制(oct返回八进制,hex返回十六进制)
ceiling(x) 返回大于x的最小整数值,取顶
exp(x) 返回值e(自然对数的底)的x次方
floor(x) 返回小于x的最大整数值,取底
greatest(x1,x2,...,xn) 返回集合中最大的值
least(x1,x2,...,xn) 返回集合中最小的值
ln(x) 返回x的自然对数
log(x,y) 返回x的以y为底的对数
mod(x,y) 返回x/y的模(余数)
pi() 返回pi的值(圆周率)
rand() 返回0到1内的随机值,可以通过提供一个参数(种子)使rand()随机数生成器生成一个指定的值。
round(x,y) 返回参数x的四舍五入的有y位小数的值
sign(x) 返回代表数字x的符号的值
sqrt(x) 返回一个数的平方根
truncate(x,y) 返回数字x截短为y位小数的结果


聚合函数(常用于group by从句的select查询中)
avg(col) 返回指定列的平均值,排除为null的值
count(col) 返回指定列中非null值的个数,排除为null的值
min(col) 返回指定列的最小值,排除为null的值
max(col) 返回指定列的最大值,排除为null的值
sum(col) 返回指定列的所有值之和,排除为null的值
group_concat(col) 返回属于一组的列值连接组合而成的结果,排除为null的值


字符串函数
ascii(char) 返回字符的ascii码值
bit_length(str) 返回字符串的比特长度
concat(s1,s2...,sn) 将s1,s2...,sn连接成字符串
concat_ws(sep,s1,s2...,sn) 将s1,s2...,sn连接成字符串,并用sep字符间隔
insert(str,x,y,instr) 将字符串str从第x位置开始,y个字符长的子串替换为字符串instr,返回结果。x从1开始算
find_in_set(str,list) 分析逗号分隔的list列表,如果发现str,返回str在list中的位置
lcase(str)或lower(str) 返回将字符串str中所有字符改变为小写后的结果
ucase(str)或upper(str) 返回将字符串str中所有字符转变为大写后的结果
left(str,x) 返回字符串str中最左边的x个字符
length(s) 返回字符串str中的字符数
ltrim(str) 从字符串str中切掉开头的空格
position(substr,str) 返回子串substr在字符串str中第一次出现的位置
quote(str) 用反斜杠转义str中的单引号
repeat(str, x) 返回字符串str重复x次的结果
reverse(str) 返回颠倒字符串str的结果
right(str,x) 返回字符串str中最右边的x个字符
rtrim(str) 返回字符串str尾部的空格
strcmp(s1,s2) 比较字符串s1和s2,相同返回0,不同返回1
trim(str) 去除字符串首部和尾部的所有空格


日期和时间函数
curdate()或current_date() 返回当前的日期
curtime()或current_time() 返回当前的时间
date_add(date,interval int keyword) 返回日期date加上间隔时间int的结果(int必须按照关键字进行格式化),如:select date_add(current_date,interval 6 month);
date_format(date,fmt) 依照指定的fmt格式格式化日期date值
date_sub(date,interval int keyword) 返回日期date减去间隔时间int的结果(int必须按照关键字进行格式化),如:select date_sub(current_date,interval 6 month);
dayofweek(date) 返回date所代表的一星期中的第几天(1~7)
dayofmonth(date) 返回date是一个月的第几天(1~31)
dayofyear(date) 返回date是一年的第几天(1~366)
dayname(date) 返回date的星期名,英文名,如:select dayname(current_date)
from_unixtime(ts,fmt) 根据指定的fmt格式,格式化unix时间戳ts
hour(time) 返回time的小时值(0~23)
minute(time) 返回time的分钟值(0~59)
month(date) 返回date的月份值(1~12)
monthname(date) 返回date的月份名,英文名,如:select monthname(current_date)
now() 返回当前的日期和时间
quarter(date) 返回date在一年中的季度(1~4),如select quarter(current_date)
week(date) 返回日期date为一年中第几周(0~53)
year(date) 返回日期date的年份(1000~9999)


获取当前系统时间:
select from_unixtime(unix_timestamp());
select extract(year_month from current_date);
select extract(day_second from current_date);
select extract(hour_minute from current_date);
返回两个日期值之间的差值(月数):select period_diff(200302,199802);


在mysql中计算年龄:
select date_format(from_days(to_days(now())-to_days(birthday)),'%y')+0 as age from employee;
这样,如果brithday是未来的年月日的话,计算结果为0。

下面的sql语句计算员工的绝对年龄,即当birthday是未来的日期时,将得到负值。
select date_format(now(), '%y') - date_format(birthday, '%y') -(date_format(now(), '00-%m-%d') <date_format(birthday, '00-%m-%d')) as age from employee
————————————————

原文链接:https://blog.csdn.net/cgs666/article/details/80996333

原文地址:https://www.cnblogs.com/429lirui/p/14776397.html