目录
求四舍五入值round(n,d),n表示原数,d表示小数位置,默认小数为0
一、字符串函数
-
拼接字符串concat(str1,str2...)
🧐例1:拼接 12, 34, ‘ab’
select concat (12, 34, 'ab' );
🧐例2:将学生表的名字和家乡拼接,显示拼接 xxx '的家乡是:'xx
select nane, hometown, concat(nane, '的家乡是:', hometown) from students
💦技巧:
有些程序功能不用程序再写, 可以查询后用拼接方式,直接显示出网站的效果,相对于可以做出一些编程功能
-
包含字符个数 length(str)
🧐例1:’abc‘包含个数
select length('abc');
🧐例2:中文字符包含个数
运行中文:
select length('我')
与varchar的意思不一样,varchar无论是中文还是英文都是一个字符,
length返回是字节。
应用:
-- select * from students where nane like '__' --等同于 select * from students where length(nane) = 6
-
截取字符串
🔸 left(str,len):返回字符串str的左端len个字符
🔸 right(str,len):返回字符串str的右端len个字符
🔸 substring(str, pos, len):返回字符串str的位置pos起len个字符
🧐例1:截取'abc123'的第二个位置后3个字符
select substring ('abc123', 2, 3);
🧐例2:截取学生表的学生的姓
-- 求学生的姓
select left(nane, 1) from students
如:注册网站的时候,注册的名称可能就显示 ‘王** ’
-
去除空格
🔸 ltrim(str):返回删除了左空格的字符串str
🔸 rtrim(str):返回删除了右空格的字符串str
🧐例1:删除' bar '左边空格
select ltrim(' bar ');
🧐例2:删除' bar '右边空格
select rtrim(' bar ');
-
大小写转换,函数如下
🔸lower(str)
🔸upper(str)
🧐例1:将‘aBcP’ 转换成小写
select lower('aBcP');
二、数学函数
-
求四舍五入值round(n,d),n表示原数,d表示小数位置,默认小数为0
select round(1.6);
-
求x的y次幂 pow(x,y)
select pow(2, 3);
-
获取圆周率PI()
select PI();
-
随机数rand(),范围值为0-1.0的浮点数
select rand();
🧐 例1:若想要一个1-10 整数的结果
select round(rand() * 10);
🧐例2:随机从一个数据表取一条数据
select *, rand() from students order by rand() limit 1
--rand() 可以不显示
select * from students order by rand() limit 1
三、日期时间函数
-
当前日期current_date0
select current_date();
-
当前时间current_time0
select current_time();
-
当前日期时间now()
select now();
-
日期格式化date_format(date,format)
🔹参数format可选值如下:
%Y 获联年,返回完整年份
%y 获联年,返回简写年份%m 获取月,返回月份
%d 获取日,返回天值
%H 获取时,返回24进制的小时数
%h 获取时,返回12进制的小时数
%i 获取分,返回分钟数
%s 获取秒,返回秒数
🧐 例1:将使用-拼接的日期转换为使用空格拼接
select date_format('2019-12-21', '%Y %m %d');
🧐 例2:格式化当前时间
select date_format(now(), '%Y/%m/%d %H:%i:%s');
四、流程控制
-
case语法:等值判断
-
说明:
当值等于某个比较值的时候,对应的结果会被返回;
如果所有的比较值都不相等则返回else的结果;
如果没有else并且所有比较值都不相等则返回null
case 值 when 比较值1 then 结果1 when 比较值2 then 结果2 ... else 结果 end
例:
select
case 1
when 1 then 'one'
when 2 then 'two'
else 'zero' end as result;
🧐 例1:将学生表的女生姓后加‘美女’,男生姓后加‘帅哥’
select nane, sex,
case sex
when '男' then concat(left(nane, 1),'帅哥')
when '女' then concat(left(nane, 1),'美女')
else 'xx' end as 结果
from students