Loading

MySQL学习笔记-函数

MySQL-常用函数

select {函数}({参数});
  • select是查询用的,用来展示函数返回值。

一. 字符串函数

  • 常用的字符串函数:

image-20230225203321808

1. concat 拼接

select concat('Hello','World');

image-20230226204115992

2. lower 转小写

select lower('Hello World');

image-20230226204229680

3. upper 转大写

select upper('Hello World');

image-20230226204317428

4. lpad 左填充

select lpad('YS',10,'-');

image-20230226204729123

5. rpad 右填充

select rpad('YS',10,'-');

image-20230226204741000

6. trim 去前后空格

select trim('   Hello World   ');

image-20230226204755394

7. substring 切割字符串

select substring('Hello World',11,5);

image-20230226204847833

  • 起始位置从1开始算。

二. 数值函数

  • 常用的数值函数:

image-20230226205156429

1. ceil 向上取整

select ceil(1.1);

image-20230226205816164

2. floor 向下取整

select floor(1.9);

image-20230226205842642

3. mod 求模

select mod(9,5);

image-20230226205855333

4. rand 返回0-1随机数

select rand();

image-20230226205908113

5. round 四舍五入

select round(rand(),6);

image-20230226205923148

三. 日期函数

  • 常用的日期函数

image-20230226210200756

1. curdate 返回当前日期

select curdate();

image-20230226211047486

2. curtime 返回当前时间

select curtime();

image-20230226211103567

3. now 返回当前日期和时间

select now();

image-20230226211136490

4. year 获得指定date的年份

select year({date});
  • date可以用日期或日期+时间

image-20230226211214872

5. month 获得指定date的月份

select month({date});

image-20230226211227944

6. day 获得指定date的日期

select day({date});

image-20230226211238813

7. date_add 返回一个date加上一个间隔后的时间

select date_add({date},interval {间隔} {间隔的单位});
  • 间隔的单位:年(year)/月(month)/日(day)

image-20230226211304289

8. datediff 返回两个date间的天数

select datediff({date1},{date2});
  • 如果date1比date2早,返回的则是负数。

image-20230226211415452

四. 流程函数

流程函数可以在SQL语句中实现条件筛选,从而提高语句的效率。

  • 常用的流程函数

image-20230226211538478

1. if 判断

select if({值},{正确的返回值},{错误的返回值});

image-20230226213011771

2. ifnull 判断是否空

select ifnull({值1},{值2});
  • 空字符串('')不为算判断中的空,NULL才算。

image-20230226213048949

3. case 多重判断

# 判断值是否为True
select case 
				when [{值1}]		#当值1为true时,返回返回值1
				then [{返回值1}]
				...
				else [{最终返回值}] #如果前面的值都不为true,返回最终返回值
				end;

# 判断值
select  case [{变量}]
				when [{值1}]		#当变量等于值1时,返回返回值1
				then [{返回值1}]
				...
				else [{最终返回值}] #如果变量都不等于前面的值,返回最终返回值
				end;

image-20230226214346447

image-20230226214252321

posted @ 2023-02-26 21:47  YellowSeaa  阅读(16)  评论(0编辑  收藏  举报