Mysql使用SUBSTR对查询出的某一列数据进行随意分割

一、需求

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)

四、总结

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章