Mysql – Set all images name of a product to the same field in other table separated by comma in MySQL

MySQL

I'm using MariaDB v10.1.31. I have 2 tables:

Product_images (created from a .csv import).

product_reference | name

REF.001           | example_image_1.jpg   
REF.001           | example_image_2.jpg     

Importer* (created to store all the data I need from others tables).

sku     | images

REF.001 | null    

How could I update Importer to show the following?

sku     | images

REF.001 | example_image_1.jpg,example_image_2.jpg

*Data in Importer would be to export in .csv and be able to import in WooComerce, this is why I need to import the images by this way.

Best Answer

You can use GROUP_CONCAT().

UPDATE importer 
JOIN (
    SELECT product_reference, GROUP_CONCAT(name) AS name
    FROM Product_images 
    GROUP BY product_reference
) pi ON importer.sku= pi.product_reference
SET importer.images = pi.name;

I should mention though, that your schema design may not be the best, depending on what you want to do. Read about normal forms, if you don't know what that is. A OLTP database usually is in at least 3rd normal form. Comma separated values violate the 1st normal form already.

Related Question