MySQL实现split函数相同的功能

需求

使用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 则分隔符是";"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值