需求
使用MySQL实现类似于String的split函数的功能。
一、场景描述
一个仓库中存储很多以逗号分隔的商品,以SQL对商品进行拆分。
二、实现逻辑
2.1创建仓库
# 创建一个用于存储商品的仓库
create table store
(
id int auto_increment primary key comment '主键id',
title varchar(255) comment '仓库名称',
sku_id varchar(255) comment '该仓库存储的商品集 以","分割'
) comment '仓库';
2.2向仓库中插入数据
# 初始化仓库信息
insert into store (id, title, sku_id)
values (1, '仓库一', '1,2,4'),
(2, '仓库二', '3,2,5');
2.3创建商品信息
# 商品的详细信息
create table sku
(
id int auto_increment primary key comment '主键id',
title varchar(255) comment '商品名称'
) comment '商品详情';
2.4向商品中插入数据
# 初始化商品信息
insert into sku (id, title)
values (1, 'iphone'),
(2, '华为'),
(3, '小米'),
(4, 'vivo'),
(5, 'oppo'),
(6, '诺基亚');
2.5实现查询
# 选出仓库中存储的商品信息
select temp.store_id , s.title as store_title, s.sku_id as store_sku_str,temp.sku_id as sku_id, s2.title as sku_title
from (
SELECT s.id as store_id,
SUBSTRING_INDEX(SUBSTRING_INDEX(s.sku_id, ',', help_topic_id + 1),
',',
-1) AS sku_id
FROM mysql.help_topic,
store s
WHERE help_topic_id < LENGTH(s.sku_id) -
LENGTH(REPLACE(s.sku_id, ',', '')) + 1
) temp
inner join store s on s.id = temp.store_id
inner join sku s2 on temp.sku_id = s2.id;
上面的查询中的分隔符","是数据库中存储的分隔符 如 数据库中存储:1,2,3则分隔符是"," 如果数据库中存储的是:1;2;3 则分隔符是";"