使用MySQL實現逗號分隔字符串的拆分可以使用FIND_IN_SET函數來實現:
FIND_IN_SET函數可以在逗號分隔的字符串中查找指定的值,并返回其位置。結合SUBSTRING函數,可以實現字符串的拆分。
示例代碼如下:
SELECT SUBSTRING('字符串1,字符串2,字符串3', 1, FIND_IN_SET(',', '字符串1,字符串2,字符串3') - 1) AS part1,
SUBSTRING('字符串1,字符串2,字符串3', FIND_IN_SET(',', '字符串1,字符串2,字符串3') + 1, FIND_IN_SET(',', '字符串1,字符串2,字符串3', FIND_IN_SET(',', '字符串1,字符串2,字符串3') + 1) - FIND_IN_SET(',', '字符串1,字符串2,字符串3') - 1) AS part2,
SUBSTRING('字符串1,字符串2,字符串3', FIND_IN_SET(',', '字符串1,字符串2,字符串3', FIND_IN_SET(',', '字符串1,字符串2,字符串3') + 1) + 1) AS part3;
解釋:
- SUBSTRING('字符串1,字符串2,字符串3', 1, FIND_IN_SET(',', '字符串1,字符串2,字符串3') - 1):返回第一個逗號之前的部分,即字符串1。
- SUBSTRING('字符串1,字符串2,字符串3', FIND_IN_SET(',', '字符串1,字符串2,字符串3') + 1, FIND_IN_SET(',', '字符串1,字符串2,字符串3', FIND_IN_SET(',', '字符串1,字符串2,字符串3') + 1) - FIND_IN_SET(',', '字符串1,字符串2,字符串3') - 1):返回第一個逗號和第二個逗號之間的部分,即字符串2。
- SUBSTRING('字符串1,字符串2,字符串3', FIND_IN_SET(',', '字符串1,字符串2,字符串3', FIND_IN_SET(',', '字符串1,字符串2,字符串3') + 1) + 1):返回第一個逗號和第三個逗號之間的部分,即字符串3。
上一篇
如何用mysql查找前10條記錄下一篇
如何使用mysql實現定時任務
2023-12-09

2023-12-09

2023-12-09

2023-12-09

2023-12-09

2023-12-09

2023-12-09

2023-12-09

2023-12-09

2023-12-09

2023-12-09

2023-12-09

2023-12-09

2023-12-09

2023-12-09