数据库操作(函数)

函数是一段可以直接被另外一段程序调用的程序或代码

一。字符串函数

1.concat(s1,s1....sn):字符串拼接,将s1,s2,sn拼接为一个字符串

例如: select concat("hello","world");

2.lower(str):将字符串str全部转为小写

例如: select lower("HELLO");

2.upper(str):将字符串str全部转为大写

例如: select upper("hello");

3.lpad(str,n,pad):左填充,用字符串pad对str的左边进行填充,达到n个字符串长度

例如:select lpad("hello",10,"*");

3.rpad(str,n,pad):右填充,用字符串pad对str的右边进行填充,达到n个字符串长度

例如:select rpad("hello",10,"*");

4.trim(str):去掉字符串头部和尾部的空格

例如:select trim("  hello world  ");

5.substring(str,start.len):返回从字符串str从start位置起到len个长度的字符串

例如: select substring("hello world",1,5);

二。数值函数

1.ceil(x):向上取整

例如:select ceil(1.5)        结果为2

2.floor(x):向下取整

例如:select floor(1.5)        结果为1

3.mod(x,y):返回x/y的值,进行取余操作

例如:mod(4/3)        结果为1

4.rand():返回0~1内的随机数,结果在0~1之间进行选取

例如:select ran();

5.round(x,y):求参数x的四舍五入的值,保留y位小数

例如:select round(2.255,2);        结果为2.26

案例一:随机生成一个六位数的验证码

 select round(rand()*1000000,0);

 select lpad(round(rand()*100000,0),6,"0");

使用lpad进行左填充,round进行四舍五入去小数,rand随机生成

三。日期函数

1.curdate():返回当前日期: select curtime();

2.curtime():返回当前时间: select curtime();

3.now():返回当前日期和时间: select now();

4.year(date):获取指定date的年份: select year(now());

5.month(date):获取指定date的月份: select month(now());

6.day(date):获取指定date的日期: select day(now());

7.datediff(date1,date2):返回起始时间date1和结束时间date2之间的天数:

 select datediff("2024-5-10","2024-1-10");第一个时间减去第二个时间

8.date_add(date1,interval n day):返回起始时间过了n个时间段后(day,month,year)的时间:

select date_add(now(),interval 2 day);

案例:查询所有员工的入职天数,并且按照入职时间进行倒序排列:

select name,datediff(curdate(),enterdate) as "result" from emp orderr by result desc;

四。流程函数

1.if(value,t,f):如果value为真返回t,否则返回f

例:select if(2>1,"ok","error");

2.ifnull(value1,value2):如果value1不为空(null)则返回value1,否则返回value2

 例:select ifnull("yes","no");

3.case when[val] then [res1]...else[default] end:如果val为ture,返回rest,否则返回default默认值(表达式val为ture进行返回res1)

4.case[expr]  when[val] then [res1]...else[default] end:如果expr的值为val,返回res1,否则default默认值(表达式expr为val返回res1)

例:select name,case address when "北京" then "一线城市" else "二线城市" end from emp;

案例:统计学员的成绩,>80优秀 ,>60及格 ,否则不及格

select id,name

        case when math >=80 then "优秀" when math >=60 then "及格” else "不及格" end,

from score;

  • 17
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值