【问题标题】:Creating a Comma Seperated List from a subquery in SQL从 SQL 中的子查询创建逗号分隔列表
【发布时间】:2013-12-11 19:25:18
【问题描述】:

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

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

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    您必须使用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()

    【讨论】:

      【解决方案2】:

      对于那些使用 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
      

      【讨论】:

        猜你喜欢
        • 2021-09-12
        • 1970-01-01
        • 1970-01-01
        • 2012-05-10
        • 2015-11-29
        • 2022-01-07
        相关资源
        最近更新 更多