sql 按,拆分成多条数据
时间: 2023-09-05 18:12:55
浏览: 2018
在 SQL 中,可以使用[字符串](https://geek.csdn.net/educolumn/ba94496e6cfa8630df5d047358ad9719?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083)分割[[函数](https://geek.csdn.net/educolumn/2319d2a62911adc34b96ea572d8225a2?spm=1055.2569.3001.10083)](https://geek.csdn.net/educolumn/ba94496e6cfa8630df5d047358ad9719?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083)将一个包含多个值的[字符串](https://geek.csdn.net/educolumn/ba94496e6cfa8630df5d047358ad9719?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083)按照指定分隔符拆分成多条数据,例如:
假设有一个表格 `users`,其中有一列 `interests` 包含多个兴趣爱好,用逗号 `,` 分隔,如下所示:
| id | name | interests |
|----|--------|----------------|
| 1 | Alice | Reading,Sports |
| 2 | Bob | Movies,Travel |
| 3 | Carol | Music,Food |
| 4 | David | Sports,Travel |
| 5 | Edward | Food,Reading |
现在需要将 `interests` 字段按照逗号 `,` 拆分成多条数据,可以使用以下 SQL 语句:
```sql
SELECT id, name, TRIM(SPLIT_STR(interests, ',', 1)) AS interest
FROM users
UNION ALL
SELECT id, name, TRIM(SPLIT_STR(interests, ',', 2)) AS interest
FROM users
WHERE interests L[ike](https://geek.csdn.net/educolumn/4654d38702ca9c29a51957a5f9fc9ed5?spm=1055.2569.3001.10083) '%,%'
UNION ALL
SELECT id, name, TRIM(interests) AS interest
FROM users
WHERE interests NOT LIKE '%,%';
上述 SQL