在SQL中从子查询创建逗号分隔列表

时间:2013-12-11 10:52:51

标签: mysql sql

我正在将MySQL产品数据库从自定义网店迁移到Shopify上。在大多数情况下,我可以将旧产品数据库中的字段映射到shopify csv导入程序,但是在Shopify导入中需要一个字段 - 标签 - 作为逗号分隔列表,但这在原始数据库中以EAV格式存在。

所以这就是我要做的 - 选择一个数据子集作为单个字段:

SELECT 
id, 
name as title,
description as body,
(
    select b.attributeValue 
    from
    shop_product a,
    shop_product_attribute b 
    where 
    a.id = b.productId and
    b.attributeName="Tag"
) as tags
FROM shop_product a

不幸的是,SQL不支持返回多行的子查询:

Error: #1242 - Subquery returns more than 1 row

是否可以使用单个查询获得所需的结果?

2 个答案:

答案 0 :(得分:3)

您必须使用GROUP_CONCAT

试试这个:

SELECT 
id, 
name as title,
description as body,
(
    select GROUP_CONCAT( b.attributeValue ) as attributeValue
    from
    shop_product a,
    shop_product_attribute b 
    where 
    a.id = b.productId and
    b.attributeName="Tag"
) as tags
FROM shop_product a

请参阅 MySQL: GROUP_CONCAT()

答案 1 :(得分:0)

对于那些使用T-SQL的人来说,这可能是实现它的好方法。因为没有GROUP_CONCAT

SELECT 
id, 
name as title,
description as body,
(
    SELECT STUFF
    (
         (select ',' + b.attributeValue  
          from
          shop_product a,
          shop_product_attribute b 
          where 
          a.id = b.productId and
          b.attributeName="Tag"
          FOR XML PATH('')
          ),1,1,''
     ) 
) as tags
FROM shop_product a