一、字符串函数
- concat(str1,str2......):拼接字符串
select name ,hometown ,concat(name."的家乡是",hometown) from stu
![](https://img.haomeiwen.com/i5429406/1693e6538dc218a9.png)
- replace
(1)replace(str,from_str,to_str):把str中出现from_str的全部替换为to_str
UPDATE 表名 SET 字段名=replace(字段名, '被替换字符串', '用来替换的字符串') ;
update `news_test` set article_name = replace(article_name,'https://www.gplp.cn/','')
where web_site like "财经"
(2)replace into
replace into 表名 (id,name) values('1','aa'),('2','bb')
1.如果字段中有主键
若主键对应的值表中不存在,
则相当于insert into,向表中插入两条记录
若主键对应的值表中存在,
则不会插入数据,而是替换了表id=1,2位置的数据,
表中如果有除了id,name之外的字段都被替换为null了
2. 如果字段中无主键
此语句的作用是相当于insert into,向表中插入两条记录
- length(str):包含字符个数
一个中文是长度是3,其他是1
#查询name是两个字
select * from stu where length(name=6)
# 相当于where name like "__"
- 截取字符串
left(str,len):返回字符串 str 的前端 len 个字符
right(str,len):返回字符串 str 的后端 len 个字符
substring(str,start ,len):返回从字符串 str 的 start 位置截取长度为 len 的子字符串
#截取姓氏
select name,sex,concat(left(name,1),"某某") from stu
- 去掉前后空格,不能删除中间空格
ltrim(str):返回删除了左空格的字符串str
rtrim(str):返回删除了右空格的字符串str
trim(str):返回删除了前后空格的字符串str
select ltrim(rtrim(' abc '))
select trim(' abc ')
#abc
- 大小写转换
lower(str):变小写
upper(str):变大写
二、 数字函数
round(n,d):四舍五入 n表示原数,d表示小数位置,默认为0
pow(x,y):求x的y次幂
PI():获取圆周率
rand():随机数,值为0-1.0的浮点数
#随机0-10的整数
select round(rand()*10)
#随机从一个表中取一条记录
select * from stu order by rand() limit 1
三、 日期时间函数
current_date():当前日期 yyyy-mm-dd
current_time():当前时间 HH:MM:SS
now():当前日期时间 2020-12-10 17:53:25
date_format(date,format):日期格式化
format参数:
%Y 获取年,返回完整年份
%y 获取年,返回简写年份
%m 获取月,返回月份
%d 获取日,返回天数
%H 获取时,返回24进制的小时数
%h 获取时,返回12进制的小时数
%i 获取分,返回分数
%s 获取秒,返回秒数
select date_format(now(),'%Y-%m-%d %h:%i:%s')
四、 流程控制
case 值 when 比较值1 then 结果1 when 比较值2 then 结果2........else 结果 end
- case语法:等值判断
- 说明:当值等于某个比较值,对应的结果会被返回;如果所有的比较值都不相等则返回else的结果;如果没有else并且所有比较值都不相等则返回null
select name,sex,
case sex
when '男' then concat(left(name,1),'帅哥')
when '女' then concat(left(name,1),'美女')
else concat(left(name,1),'xx')
end as res
from stu
![](https://img.haomeiwen.com/i5429406/2f6afea7d01af0ea.png)
五、 自定义函数
![](https://img.haomeiwen.com/i5429406/b2202cc08231b841.png)
![](https://img.haomeiwen.com/i5429406/dceb568648a8323f.png)
delinitor $$
在命令行中使用,正常情况下执行语句是;回车
,delinitor
把执行语句的命令由;回车
改成$$回车
后边记得改回来delinitor ;
,这样比较习惯
![](https://img.haomeiwen.com/i5429406/a2578e880c5bf290.png)
![](https://img.haomeiwen.com/i5429406/6bf212b98845db3e.png)
网友评论