# MySQL 函数 substring\_index 的用法

**URL:** <https://www.shiqidu.com/t/topic/731>\
**Category:** 开发调优\
**Tags:** MySQL\
**Created:** [2021 年1 月 19 日 09:10 UTC](https://www.shiqidu.com/t/topic/731 "2021-01-19T09:10:27Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

作者： ![Leon](https://www.shiqidu.com/user_avatar/www.shiqidu.com/leon/32/5_2.png) [@Leon](https://www.shiqidu.com/u/Leon)\
发布日期： [2021 年1 月 19 日 09:10 UTC](https://www.shiqidu.com/t/topic/731/1 "2021-01-19T09:10:27Z")

</div>

```auto
substring_index（“待截取有用部分的字符串”，“截取数据依据的字符”，截取字符的位置N）

```

### 案例

```sql
SELECT SUBSTRING_INDEX(‘15,151,152,16’, ’ , ’ , 1); // 结果是15

```

以第一个逗号为分割截取

```sql
SELECT SUBSTRING_INDEX(‘15,151,152,16’, ’ , ’ , 2); // 结果是15,151

```

//以第二个逗号为分割截取

```sql
SELECT SUBSTRING_INDEX(‘15,151,152,16’, ’ , ’ , -1); // 结果是16

```

//从后面开始算第一个逗号

**根据自己设定顺序排序**

```sql
//根据自己设定的顺序进行排序
select id,substring_index('11000,10000,10001,3602,3600',id,1) from test 
where id in (10000,3602,3600,10001,11000)          
order by substring_index('11000,10000,10001,3602,3600',id,1) ;

```

结果是

 ![结果](https://discourse.shiqidu.com/uploads/default/original/1X/47792b750f2b74f0a77c8b6c1d61110dd4f2e4bd.png)

substring\_index( ‘1,3,2,4,6,5’, id, 1 ) 获取每个id前面的数据，比如：id=1 对于数据“1,3,2,4,6,5”，没有数据sub\_data=‘’

id=2 对于数据“1,3,2,4,6,5”，sub\_data=‘1,3,’

ORDER BY substring\_index( ‘1,3,2,4,6,5’, id, 1 ); 会根据你 “1,3,2,4,6,5”的顺序进行排序

> 原文地址 [mysql函数substring\_index的用法\_select substring-index-CSDN博客](https://blog.csdn.net/z457181562/article/details/82968702)
