MySQL 通过 分隔符 对字段拆分 即一行转多行

1.表的原始数据如下:

SELECT id,warehouse_ids FROM `test` ORDER BY warehouse_ids DESC LIMIT 1

2.根据逗号拆分查询

注意

1.分隔符需要替换成对应的字符,我这里的是逗号(,)

2.JOIN的user表是我数据库的一张表,主要的用处是使用他的自增id,自增id必须连续从1开始(1,2,3....)

3.一般会使用mysql.help_topic表代替user,由于没有这个表的权限使用user代替,

SELECT
	t.id AS 'id',
	substring_index( substring_index( t.warehouse_ids, ',', h.id  ), ',',- 1 ) AS 'warehouse_id' 
FROM
	(SELECT id,warehouse_ids FROM `test` ORDER BY warehouse_ids DESC LIMIT 1) t
	JOIN user AS h ON h.id-1 < ( char_length( t.warehouse_ids ) - char_length( REPLACE ( t.warehouse_ids, ',', '' ) ) + 1 )

参考了以下sql

SELECT
    t.id AS 'id',
    t.NAME AS '姓名',
    substring_index( substring_index( t.courses, '、', h.help_topic_id + 1 ), '、',- 1 ) AS '课程'
FROM t_student t JOIN mysql.help_topic AS h ON h.help_topic_id < ( char_length( t.courses ) - char_length( REPLACE ( t.courses, '、', '' ) ) + 1 )
;

3.参考文档

MySQL通过分隔符对字段拆分即一行转多行sql写法

mysql拆分字符串为多行(逗号等分割)

猜你喜欢

转载自blog.csdn.net/weixin_42048982/article/details/130870118