MySQL数据库常用函数

2017-08-21  本文已影响0人  CrazyLiuXP

选出表中字符的长度:char_length

select char_length(name) from customer;

计算那么列字符串长度的sin值

select sin(char_length(name)) from customer;

计算1.57的sin值

select sin(1.57)

为指定的日期添加一定的时间

这种用法下interval是关键字,需要一个数值,还需要一个单位

select DATE_ADD('2017-08-16', interval 2 MONTH);

这种方法更简单

select ADDDATE('2017-08-16',2);

获取当前日期

select CURDATE();

获取当前时间

select curtime();

获取MD5的加密函数

select MD5('testing')

MySQL还提供了几个处理null的函数

例如:
#如果name列为null,则返回‘没有名字’
select ifnull(name,'没有名字') from customer;

#如果name列等于‘张三’,则返回null
select nullif(name,'张三') from customer;

#如果name列为null,则返回”没有名字“,否则返回”有名字“
select if(isnull(name),'没有名字','有名字') from customer;

MySQL还提供了一个case函数,该函数是一个流程控制函数。case函数有两个用法.

1.case函数的第一个用法的语法格式如下:
case value
when compare_value1 then result1
when compare_value2 then result2
...
else reuslt
end

case函数用value和后边的compare_value1、compare_value2、...依次进行比较,如果value和指定的compare_value1相等,则返回对应的result,否则返回else后的result。例如如下SQL语句:

# 如果teacher为1,则返回“李老师”,为2则返回“张老师”,否则返回“其他老师”
select student_name, case teacher 
when 1 then '李老师' 
when 2 then '张老师' 
else '其他老师' 
end 
from student_table;
2.case的第二个用法的语法格式如下:
case
when condition1 then result1
when condition2 then result2
...
else result
end

在第二个用法中,condition1,、condition2都是一个返回boolean值得条件表达式,因此这种用法更加灵活。例如如下SQL语句:

# id 小于3的为初级班,3--6的为中级班,其它的为高级班
select student_name, case
when student_id<3 then '初级班' 
when student_id<=6 then '中级班' 
else '高级班' 
end 
from student_table;

分组和组函数

对于可能出现null的列,可以使用ifnull函数来处理该列。

# 计算expr列所有列的平均值
select avg(ifnull(expr, 0)) from table;
上一篇下一篇

猜你喜欢

热点阅读