将json字段中的值更改为MySQL select中其他json字段中的适当值

0vvn1miw  于 2023-07-01  发布在  Mysql
关注(0)|答案(1)|浏览(117)

我有以下简化的模式和数据:

Schema(MySQL v5.7.22)

CREATE TABLE `config_remap` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(200),
  `addons` json,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `products` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `product_name` varchar(500) DEFAULT NULL,
  `requested_remap_id` int(11) DEFAULT NULL,
  `requested_addons` json, 
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `config_remap` (`id`, `name`, `addons`) 
VALUES(1, 'Remap 1', 
'[{"id": 0,"name": "Addon 0"},
  {"id": 1,"name": "Addon 1"},
  {"id": 2,"name": "Addon 2"}
]');

INSERT INTO `products` (`id`, `product_name`, `requested_remap_id`, `requested_addons`) 
VALUES (1, 'Audi A4', 1, '[\"0\", \"2\"]');

和以下查询:

select products.id, products.product_name, products.requested_addons, config_remap.name as requested_addon
from products
    left join config_remap on config_remap.id = products.requested_remap_id

其产生以下结果:
| 产品名称|requested_addons| requested_addon| requested_addon |
| --|--|--| ------------ |
| 奥迪A4| [“0”,“2”]|重Map1| Remap 1 |
我想更改查询,以便它可以将requested_addons的ID替换为config_remap中的名称。addons。因此预期结果应该类似于:
| 产品名称|requested_addons| requested_addon| requested_addon |
| --|--|--| ------------ |
| 奥迪A4| [“插件0”,“插件2”]|重Map1| Remap 1 |
View on DB Fiddle

我使用的是MySQL 5.7.22

gijlo24d

gijlo24d1#

SELECT products.id, 
       products.product_name,
       JSON_ARRAYAGG(config_remap.addon_name) requested_addons, 
       config_remap.name requested_addon
FROM (
  SELECT cr.id, cr.name, 
         JSON_UNQUOTE(JSON_EXTRACT(cr.addons, CONCAT('$[', numbers.pos, '].id'))) addon_id, 
         JSON_UNQUOTE(JSON_EXTRACT(cr.addons, CONCAT('$[', numbers.pos, '].name'))) addon_name
  FROM config_remap cr
  CROSS JOIN (SELECT 0 pos UNION SELECT 1 UNION SELECT 2 UNION SELECT 3) numbers
  ) config_remap
JOIN (
  SELECT pr.id, pr.product_name,  pr.requested_remap_id, 
         JSON_UNQUOTE(JSON_EXTRACT(pr.requested_addons, CONCAT('$[', numbers.pos, ']'))) addon_id
  FROM products pr
  CROSS JOIN (SELECT 0 pos UNION SELECT 1 UNION SELECT 2 UNION SELECT 3) numbers
  ) products USING (addon_id)
GROUP BY 1, 2, 4;

| 产品名称|requested_addons| requested_addon| requested_addon |
| --|--|--| ------------ |
| 奥迪A4| [“插件0”,“插件2”]|重Map1| Remap 1 |
fiddle
一般来说,有不超过15个插件可供选择。- Milen Mihalev
相应地展开numbers合成表。

相关问题