gpt4 book ai didi

mysql - 如何在子查询中使用 WHERE IN 和字符串列中的值?

转载 作者:行者123 更新时间:2023-11-29 09:51:15 25 4
gpt4 key购买 nike

我在将 WHERE IN 与列值一起使用时遇到问题

我有如下数据

餐 table 服务

id  name            sd_ids
1 House Cleaning 1,2

餐 table 服务详情

id  name
1 living room
2 bedroom

架构

CREATE TABLE IF NOT EXISTS `service` (
`id` int(6) unsigned NOT NULL,
`name` varchar(200) NOT NULL,
`sd_ids` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `service` (`id`, `name`,`sd_ids`) VALUES
('1','House Cleaning','1,2');

CREATE TABLE IF NOT EXISTS `service_detail` (
`id` int(6) unsigned NOT NULL,
`name` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `service_detail` (`id`, `name`) VALUES
('1','living room'),
('2','bedroom');

我已经尝试过了

SELECT *,
(
SELECT
GROUP_CONCAT(name)
from service_detail
where id in(service.sd_ids)
) as service_detail
FROM service;

但结果不是我想要的

id  name            sd_ids  service_detail
1 House Cleaning 1,2 living

我把架构和我的测试放在这里 http://sqlfiddle.com/#!9/49c34e/7

我想要实现的结果是显示如下所示的结果

id  name            sd_ids  service_detail
1 House Cleaning 1,2 living room,bedroom

我知道这种模式不是最佳实践,但我需要建议来实现这一目标。

谢谢

最佳答案

您可以在加入条件中使用 FIND_IN_SET 加入:

SELECT
s.id,
s.name,
s.sd_ids,
GROUP_CONCAT(sd.name ORDER BY sd.id) AS service_detail
FROM service s
INNER JOIN service_detail sd
ON FIND_IN_SET(sd.id, s.sd_ids) > 0
GROUP BY
s.id,
s.name,
s.sd_ids;

enter image description here

Demo

一般来说,您应该避免在 SQL 表中存储 CSV 数据。 CSV 数据代表非标准化数据,并且很难使用(参见上述查询)。相反,请将每个服务 ID 分解为单独的记录以获得最佳结果。

关于mysql - 如何在子查询中使用 WHERE IN 和字符串列中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54760911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com