版本:mysql 8.x
mysql 没有 split() 这样的函数,但可以用 substring_index 或 json_table 实现“按分隔符拆列”。
下面给出 官方推荐 + 实战写法,每个都能直接复制运行。
1. 核心函数速览
函数 | 作用一句话 | 语法 |
---|---|---|
substring_index(str, delim, n) | 返回第 n 个分隔符前/后的子串 | substring_index('a,b,c',',',2) → ‘a,b’ |
json_table(json, path columns(…)) | 把 json 数组拆成行 | 见案例 4 |
regexp_substr / regexp_replace | 正则切分/替换 | mysql 8 支持,见案例 5 |
2. 案例实验室
准备一张表:
create table orders ( id int primary key, items varchar(100) -- 用逗号分隔的商品串 ); insert into orders values (1,'苹果,香蕉,橙子'), (2,'芒果'), (3,'桃子,葡萄'), (4,'');
案例 1 substring_index 取第 1、2、3 个元素
select id, substring_index(items, ',', 1) as item1, substring_index(substring_index(items, ',', 2), ',', -1) as item2, substring_index(items, ',', -1) as item_last from orders;
id | item1 | item2 | item_last |
---|---|---|---|
1 | 苹果 | 香蕉 | 橙子 |
2 | 芒果 | 芒果 | 芒果 |
3 | 桃子 | 葡萄 | 葡萄 |
4 |
案例 2 一行变多行(数字表法)
用递归数字表(mysql 8 cte)把任意长度的逗号串拆成行。
with recursive nums(n) as ( select 1 union all select n+1 from nums where n<20 ) select o.id, o.items, trim(substring_index(substring_index(o.items, ',', n), ',', -1)) as item from orders o join nums on n <= 1 + length(o.items) - length(replace(o.items, ',', ''));
结果
id | items | item |
---|---|---|
1 | 苹果,香蕉,橙子 | 苹果 |
1 | 苹果,香蕉,橙子 | 香蕉 |
1 | 苹果,香蕉,橙子 | 橙子 |
2 | 芒果 | 芒果 |
3 | 桃子,葡萄 | 桃子 |
3 | 桃子,葡萄 | 葡萄 |
案例 3 json_table(8.0 最优雅)
把逗号串先转成 json,再拆成行。
select o.id, t.item from orders o, json_table( concat('["', replace(items, ',', '","'), '"]'), -- 变成 ["苹果","香蕉","橙子"] "$[*]" columns(item varchar(20) path "$") ) as t;
结果与案例 2 完全一致,但写法更短更清晰。
案例 4 正则切分(regexp_substr)
按任意正则分隔符拆列。
select id, regexp_substr(items, '[^,]+', 1, 1) as item1, regexp_substr(items, '[^,]+', 1, 2) as item2, regexp_substr(items, '[^,]+', 1, 3) as item3 from orders;
id | item1 | item2 | item3 |
---|---|---|---|
1 | 苹果 | 香蕉 | 橙子 |
2 | 芒果 | null | null |
3 | 桃子 | 葡萄 | null |
4 | null | null | null |
3. 课堂小结
场景 | 推荐方案 |
---|---|
已知固定位置 | substring_index 一步到位 |
任意长度串 → 行 | 递归 cte + substring_index |
mysql 8.0 | json_table 最优雅 |
复杂正则 | regexp_substr / regexp_replace |
到此这篇关于mysql中列值分割的几种方法的文章就介绍到这了,更多相关mysql 列值分割内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论