一、需求
mysql> select * from news;
+----+----------+
| id | times |
+----+----------+
| 1 | 20200812 |
| 2 | 20200712 |
+----+----------+
2 rows in set (0.00 sec)
查询出的times
列是一个时间字符串,如何把该字符串转化为2020-08-12
这种格式呢?
二、mysql中SUBSTR函数的几种使用方式
其中,str是字符串,pos是起始位置,len是截取的长度。
- 方式1
substr(str,pos)
mysql> select SUBSTR(times,3) as "时间" from news;
+--------+
| 时间 |
+--------+
| 200812 |
| 200712 |
+--------+
2 rows in set (0.00 sec)
说明:从第三位开始截,直到结束。
- 方式二
substr(str,pos,len)
mysql> select SUBSTR(times,3,2) as "时间" from news;
+------+
| 时间 |
+------+
| 20 |
| 20 |
+------+
2 rows in set (0.00 sec)
说明:从第三位开始截,一共截2位。
- 方式三
substr(str from pos)
mysql> select SUBSTR(times from 3) as "时间" from news;
+--------+
| 时间 |
+--------+
| 200812 |
| 200712 |
+--------+
2 rows in set (0.00 sec)
说明:从第三位开始截,直到结束。
- 方式四
substr(str from pos len)
mysql> select SUBSTR(times from 3 for 3) as "时间" from news;
+------+
| 时间 |
+------+
| 200 |
| 200 |
+------+
2 rows in set (0.00 sec)
说明:从第三位开始截,截取三位。
三、利用substr、concat分割字符
mysql> SELECT CONCAT(SUBSTR(times,1,4),"-",SUBSTR(times,5,2),"-",SUBSTR(times,7,2)) as "时间" FROM `news`;
+------------+
| 时间 |
+------------+
| 2020-08-12 |
| 2020-07-12 |
+------------+
2 rows in set (0.00 sec)
四、总结
扫描二维码关注公众号,回复:
13119405 查看本文章
