MySQL——第三章 函数


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

3.1字符串函数

函数 功能
CONCAT(S1,S2…Sn) 字符串拼接
LOWER(str) 将字符串str全部转为小写
UPPER(str) 将字符串str全部转为大写
LPAD(str,n,pad) 左填充,用字符串pad对str的左边进行填充,达到n个字符串长度
RPAD(str,n,pad) 右填充,用字符串pad对str的右边进行填充,达到n个字符串长度
TRIM(str) 去掉字符串头部和尾部的空格
SUBSTRING(str,start,len) 返回字符串str从start位置起的len个长度的字符串

SELECT 函数(参数)

select concat('Hello', ' world');
select lower('Hello');
select upper('Hello');

select lpad('01', 5, '+');
select rpad('02', 5, '-');

select substring('Hello Wrold', 2, 3);
select trim('   001  jdka  ');

use itheima;
update emp set workno= lpad(workno, 5, '0');

3.2 数值函数

函数 功能
CELL(x) 向上取整
FLOOR(x) 向下取整
MOD(x,y) 返回 x/y 的模
RAND() 返回0~1内的随机数
ROUND(x,y) 求参数 x 的四舍五入的值,保留 y 位小数
-- 数值函数
select ceil(1.5);

select floor(1.5);

select mod(10,4);

select rand();

select round(8.8888888,2);

-- 生成6位数的随机验证码
select lpad(round(rand()*1000000,0),6,'0');

3.3 日期函数

在这里插入图片描述

-- 日期函数
select current_date;
select current_time;
select curdate();
select now();

select year(now());
select month(now());
select day(now());

select date_add(now(),interval 90 month );
select date_add(now(),interval 90 year);

select datediff('2024-1-1',now());

-- 查询所有员工的入职天数,并根据入职天数倒序排序
select name,datediff(curdate(),entrydate) as '入职天数'
from emp order by 入职天数 desc ;

3.4 流程函数

在这里插入图片描述

-- 流程函数
select if(true,'ok','Error');
select if(false,'ok','Error');

select ifnull('ok','Error');
select ifnull(null,'Error');

select
   name,
   case workaddress when '北京' then '一线城市' when '上海' then '一线城市' else '二线城市' end
from emp;

在这里插入图片描述
在这里插入图片描述

create table score(
   id int comment 'ID',
   name varchar(20) comment '姓名',
   math int comment '数学',
   english int comment '英语',
   chinese int comment '语文'
) comment '学员成绩表';

insert into score (id, name, math, english, chinese)
values (1,'Tom',67,88,95),
      (2,'Rose',23,66,90),
      (3,'Jack',56,98,76);
select
   id,
   name,
   case when math >= 85 then '优秀' when math >= 60 then '及格' else '不及格' end as '数学',
   case when english >= 85 then '优秀' when math >= 60 then '及格' else '不及格' end as '英语',
   case when chinese >= 85 then '优秀' when math >= 60 then '及格' else '不及格' end as '语文'
from score;

相关推荐

  1. MySQLMySQL的基本函数

    2024-02-12 20:00:01       61 阅读
  2. MySQL笔记-15_存储过程与函数

    2024-02-12 20:00:01       44 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-12 20:00:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-12 20:00:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-12 20:00:01       82 阅读
  4. Python语言-面向对象

    2024-02-12 20:00:01       91 阅读

热门阅读

  1. 快速部署开发常用软件

    2024-02-12 20:00:01       56 阅读
  2. GMP怎么调度goroutine(重点)

    2024-02-12 20:00:01       36 阅读
  3. 全面了解C语言宏的原理和应用

    2024-02-12 20:00:01       54 阅读
  4. Acwing154滑动窗口

    2024-02-12 20:00:01       52 阅读
  5. 8 scala的伴生对象

    2024-02-12 20:00:01       52 阅读
  6. 《AI绘画从入门到精通》专栏总目录

    2024-02-12 20:00:01       66 阅读
  7. 树莓派与vnc的错误 树莓派自启vnc虚拟桌面

    2024-02-12 20:00:01       62 阅读