最近迁移数据对字符串操作的多了,难免要查一些数据库常用的操作,查的多了,就该总结一下常用的函数使用了。本篇讲MYSQL的,SQLServer回头有时间再说,毕竟是撸主是java程序员。
分四类吧,主要是前三类,第四类不知道归哪里,又不好自己归一篇。
- 截取
left(str, length) 从左开始截取length个字符right(str, length)从右开始截取length个字符substring(str, pos) 从第pos位开始截取
substring(str, pos, length) 从第pos位开始截取length个字节substring_index(str,delim,count) 从头开始截取,到关键字delim出现的次数count截止,(第几次截止)如substring_index(str,'.',2)则到第二次数显.是截止
- 拼接
‘+’:我们代码中常用+作为字符串的拼接,在mysql中倘若你来了'abc'+'123',我只能告诉你结果是123,他们会把字符当做0跟数字相加,所以在mysql中那个+是真的加啊。
‘CONCAT’:字符串的拼接操作,concat(str1,str2,str3)意思是将三个字符拼接,没有参数多少限制,相当于代码中字符串的+。 - replcae 替换
1 replace into:replace into table (id,name) values('1','aa'),('2','bb')=insert into table (id,name) values('1','aa'),('2','bb') .如果主键1,2存在则不做操作。2 replace :replace(object,search,replace) 用replace替换字符串object中所有search
-
case两种用法:
1简单case: case sex when 1 then ‘男’ when 0 then '女' else '未知' end as sex2条件case: case when score>90 then '优秀' when score<90 and score>80 then '不优秀' else '不及格' end as score