mysql对查出来的数据进行切割_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)

四、总结

a24288252dce5980b8f7042aa1843833.png

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值