简体   繁体   中英

Creating a Comma Seperated List from a subquery in SQL

I am migrating a MySQL product database from a custom webstore onto Shopify. For the most part, I can just map fields from the old product database to the shopify csv importer, however one field - Tags - is required as a comma seperated list in the Shopify import, but this exists in EAV format in the original database.

So this is what I'm trying to do - select a subset of data as a single field:

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

Unfortunately, SQL doesn't support subqueries that return more than a single row:

Error: #1242 - Subquery returns more than 1 row

Is it possible to get t he required result using a single query?

You have to use GROUP_CONCAT .

Try this:

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

Refer to : MySQL: GROUP_CONCAT()

For those who use T-SQL, this can be a good alternative to acheive it. as there is no 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM