一、需求
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)