1.行转列,
SELECT
substring_index(substring_index('1,2,3,4',',', b.help_topic_id + 1), ',', -1) result
FROM
mysql.help_topic b
where
b.help_topic_id < (LENGTH('1,2,3,4') - LENGTH(REPLACE('1,2,3,4', ',', '')) + 1);
比较好奇的是mysql.help_topic 其实充当的只是一个排序编号
替代mysql.help_topic的方法
create table if not EXISTS tab_help_topic (
help_topic_id bigint(20) not null AUTO_INCREMENT,
PRIMARY KEY (help_topic_id)
);
执行插入多次,主要用的是用id自增计数
INSERT INTO tab_help_topic () VALUES (); -- 多次执行,批量插入
插入或者说计数几次,取决于最大需要分割的行数执行下面sql直接得出,不放心可以多执行几次插入。如果计数次数小于最大字段分割行数,得到的结果就是超出部分会没有。
SELECT MAX(LENGTH(a.`userName`) - LENGTH(REPLACE(a.`userName`, ',', '' )) + 1) FROM `tbl_name` a;
注意点,mysql.help_topic与我们自己创建tab_help_topic 区别 自增id从1开始
修改sql后
SELECT
substring_index(substring_index('1,2,3,4',',', b.help_topic_id ), ',', -1) result
FROM
tab_help_topic b
where
b.help_topic_id <= (LENGTH('1,2,3,4') - LENGTH(REPLACE('1,2,3,4', ',', '')) + 1);
补充说明,还有一种是tab_help_topic是id被某种原因断层了,比如少了2,数据库中只有1,2,4
那边查询出来结果就会少了分割出来的第二行。