mysql csv 字段名_mysql加入csv字段?

bd96500e110b49cbb3cd949968f18be7.png

I have three tables like below

CREATE TABLE IF NOT EXISTS `cat` (

`id` int(15) NOT NULL AUTO_INCREMENT,

`color_options` varchar(255) NOT NULL DEFAULT '',

PRIMARY KEY (`id`)

);

INSERT INTO `cat` (`id`, `color_options`) VALUES (1, '1,2,3,4');

CREATE TABLE IF NOT EXISTS `template` (

`id` int(15) NOT NULL AUTO_INCREMENT,

`cat_id` int(15) NOT NULL DEFAULT '0',

PRIMARY KEY (`id`)

);

INSERT INTO `template` (`id`, `cat_id`) VALUES (1, 1);

CREATE TABLE IF NOT EXISTS `color` (

`id` int(15) NOT NULL AUTO_INCREMENT,

`name` varchar(255) NOT NULL DEFAULT '',

`code` varchar(6) NOT NULL DEFAULT '',

PRIMARY KEY (`id`)

);

INSERT INTO `color` (`id`, `name`, `code`) VALUES

(1, 'Black', '000000'),

(2, 'Red', 'FF0000'),

(3, 'Blue', '0000FF'),

(4, 'Green', '00FF00');

If I run

SELECT *

FROM template

LEFT JOIN cat ON cat.id=template.id;

then I will get

id cat_id color_options

1 1 1,2,3,4

How do I get the color options in text(Black,Red,BLue,Green) instead of plain numbers?

I tried using join but it doesn't work on csv field.

Thanks in advance

解决方案

A sub query with GROUP_CONCAT()

SELECT *,(SELECT GROUP_CONCAT(name) FROM color WHERE CONCAT(',',cat.color_options,',') LIKE CONCAT('%,',color.id,',%')) color_options_text

FROM template

LEFT JOIN cat ON cat.id=template.id

Someone else used a function new to me, this also works & is cleaner to read

SELECT *,(SELECT GROUP_CONCAT(name) FROM color WHERE FIND_IN_SET(color.id,cat.color_options)) color_options_text

FROM template

LEFT JOIN cat ON cat.id=template.id

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值