【问题标题】:How to concatenate multiple rows of subquery results in mysql?如何在mysql中连接多行子查询结果?
【发布时间】:2015-06-01 10:39:19
【问题描述】:

我想用IN() 函数将所有匹配的数据逗号与子查询分开连接。但是这个查询通过连接只返回一个数据,如果我传递像IN(1,2,3)这样的静态ID,则返回与ID对应的所有数据。

例子:

(SELECT GROUP_CONCAT(product_name SEPARATOR ", ") AS pname FROM tbl_product WHERE product_id IN (b.product_id)) as product

返回一条记录:

(SELECT GROUP_CONCAT(product_name SEPARATOR ", ") AS pname FROM tbl_product WHERE product_id IN (1,2,3)) as product

返回 3 条记录:

b.product_id 列包含逗号分隔值。

这是我的查询:

$this->db->select('b.*, st.description as skin_tone, sp.description as skin_profile, sc.description as skin_concerns, pua.product, pua.producttype, pua.category, ua.description as action, t.description as type,
    (SELECT GROUP_CONCAT(product_name SEPARATOR ", ") AS pname FROM tbl_product WHERE product_id IN (b.product_id)) as product', false);

$this->db->from('tbl_basket b');
$this->db->join('tbl_skin_tone st', 'st.id = b.skin_tone_id', 'LEFT');
$this->db->join('tbl_skin_profile sp', 'sp.id = b.skin_profile_id', 'LEFT');
$this->db->join('tbl_skin_concerns sc', 'sc.id = b.skin_concern_id', 'LEFT');       
$this->db->join('tbl_product_updated_all pua', 'pua.id = b.product_id', 'LEFT');
$this->db->join('tbl_user_action ua', 'ua.id = b.action_id', 'LEFT');
$this->db->join('tbl_type t', 't.id = b.type_id', 'LEFT');  
$this->db->where('b.customer_id', $reminderProductID);  

$query = $this->db->get();

return $query->result_array();

请让我知道我哪里做错了。

【问题讨论】:

  • 这是什么编程语言/框架?请添加相应的标签。
  • 我正在使用 PHP 的 codeigniter 框架。
  • 我不明白你在问什么(尽管 GL 似乎是这样)。如果您愿意,请考虑遵循这个简单的两步操作过程: 1. 如果您还没有这样做,请提供适当的 DDL(和/或 sqlfiddle),以便我们可以更轻松地复制问题。 2. 如果您尚未这样做,请提供与步骤 1 中提供的信息相对应的所需结果集。

标签: mysql sql


【解决方案1】:

这个表达式:

SELECT GROUP_CONCAT(product_name SEPARATOR ", ") AS pname
FROM tbl_product
WHERE product_id IN (b.product_id)) as product

不符合您的预期。当product_id 是一个字符串时,比如'1,2,3',那么它是in 列表中的一个 元素,而不是三个。

解决问题的正确方法是不要将列表存储为逗号分隔的列表。 SQL 具有用于存储列表的出色数据结构;它被称为“表”,而不是“字符串”。此外,将数字存储为字符串是一个非常糟糕的主意。

在您找出正确的数据结构时,有一种变通方法。那就是函数find_in_set()

WHERE find_in_set(product_id, b.product_id) as product

【讨论】:

  • 非常感谢 Gordon Linoff find_in_set() 工作正常。
猜你喜欢
  • 2021-09-25
  • 2016-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-25
相关资源
最近更新 更多