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

标签 mysql sql

我在将 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/

相关文章:

php - 将详细信息添加到用户配置文件(将登录的用户和当前演出插入新表的查询)

mysql - SQL 中的连接顺序是否重要(特定于 MySQL)- FROM 子句中的 NOT 表

mysql - 如何仅求和特定行的值?

mysql - 多个 WHERE MYSQL 语句中出现 'LIKE' 错误

sql - 为什么 'delete from table' 需要 0 时间而 'truncate table' 需要很长时间?

php - 在mysql中保存php函数

sql - 返回没有匹配条目的所有日期

php - 从 PDOException $e 返回特定项目

MySQL 索引未使用

php - 拉维 SQL Server : SQLSTATE[HY000]: [unixODBC][Microsoft][ODBC Driver 13 for SQL Server]Protocol error in TDS stream