MySQL疑难杂症
拆分字符串
例如(将chry中把每个名字取出来)

SELECT * ,SUBSTRING_INDEX(chry,'、',1) AS rycf FROM juhua_dajiandu.`jh_jg_szyd_jchyxx` -- 用、拆开,取第一个
UNION
SELECT * ,SUBSTRING_INDEX(SUBSTRING_INDEX(chry,'、',2),'、',-1) AS i FROM juhua_dajiandu.`jh_jg_szyd_jchyxx` -- 用、拆开,取前两个,然后再用、拆开,取倒数第一个
这样就会把所有名字都拆出来了,然后选择不同的名字列,进行union去重操作
效果

常用方法
SELECT
substring_index( substring_index( a.mes_no, ',', b.help_topic_id + 1 ), ',', - 1 ) AS mesno
FROM
dwr_mt_production_problem_warn_f a
JOIN mysql.help_topic b ON b.help_topic_id < ( length( a.mes_no ) - length( REPLACE ( a.mes_no, ',', '' )) + 1 )
合并数据,案例(将两个订单号合并到一起)

不同以往,这个下面的数据只有单号非空,其余全是空字段
方法1(8版本):
select t1.*,
sum(t1.num) over(order by t1.id)
from tab1 t1
方法2(7版本):
select t1.*,
@sum:=@sum+t1.num
from tab1 t1, (select @sum:=0) t2
都是累加原理(先编辑一列辅助数据,有数据的标1,需要合并上去的数据标2),只是7版本没有开窗函数,只能定义一个变量,然后对辅助列累加求和,最后再用这列新生成的列聚合,把订单group_concat就好了
效果

分组筛选,案例(如下数据,需要用id分组,保留num列数字连续并且是三个或三个以上连续的数据才保留)

方法
with tab1 as (
select t1.*,
case when lag(t1.num) over(order by t1.id) + 1 = t1.num
then 0
else 1
end ct,
@rownum:=@rownum+1 rn
from test1129 t1, (select @rownum:=0) t2
)
, tab2 as (
select t1.*,
sum(t1.ct) over(partition by t1.id order by t1.rn) gp
from tab1 t1
)
, tab3 as (
select t1.*,
count(*) over(partition by t1.id, t1.gp) cot
from tab2 t1
)
select t1.id,
t1.num
from tab3 t1
where t1.cot >= 3
;
结果如下

思路

