mysql 字符串逗号隔开转多行
时间: 2023-11-03 07:55:32 浏览: 43
可以使用MySQL内置函数`replace`和`substring_index`来将逗号隔开的字符串转为多行,具体做法如下:
假设我们有一个表`t`,其中有一个字段`str`存储了逗号隔开的字符串:
```
mysql> select * from t;
+----+--------------+
| id | str |
+----+--------------+
| 1 | a,b,c |
| 2 | d,e,f,g,h,i |
+----+--------------+
```
我们想将这个逗号隔开的字符串转为多行,可以使用如下SQL语句:
```
mysql> select id, replace(substring_index(str, ',', n), ' ', '') as str
from t
join (select 1 as n union all select 2 union all select 3 union all select 4
union all select 5 union all select 6 union all select 7) nums
on char_length(str)
- char_length(replace(str, ',', ''))
>= n - 1;
```
解释一下上面的SQL语句:
- `substring_index(str, ',', n)`:取出逗号隔开的字符串中第n个逗号前的子串;
- `replace(..., ' ', '')`:去除取出的子串中的空格;
- `join (select 1 as n union all select 2 union all select 3 union all select 4
union all select 5 union all select 6 union all select 7) nums`:使用一个子查询`nums`生成一个包含数字1~7的临时表,用于将逗号隔开的字符串转为最多7行;
- `char_length(str) - char_length(replace(str, ',', ''))`:计算逗号隔开的字符串中逗号的个数;
- `>= n - 1`:将第n个逗号前的子串转为一行时,需要保证逗号的个数不少于n-1个。
执行上面的SQL语句后,可以得到如下结果:
```
+----+------+
| id | str |
+----+------+
| 1 | a |
| 1 | b |
| 1 | c |
| 2 | d |
| 2 | e |
| 2 | f |
| 2 | g |
| 2 | h |
| 2 | i |
+----+------+
```
其中,每个逗号隔开的子串已经被转为了多行。