Question

Forgive me if I get some terms wrong, still trying to learn advanced mySql queries. I am trying to export data from a ecommerce platform, and some of the data I need is in lookup tables, the issue is the one lookup table I have can have more than 1 value associated, and the system I need to get the data into requires a specific format for that column.

I am using zen cart as my source if that helps, and below is the query.

Select zp.products_id as id, zpd.products_name as name, products_price_w as cost, products_price as price, zp.products_date_added as date_created, zp.products_image as thumbnail
FROM `zen_products` as zp
LEFT JOIN `zen_products_description` as zpd ON zp.products_id = zpd.products_id
WHERE zp.products_status = 1
ORDER BY zp.products_id ASC;

What I need is theres a look up table that tells me what categories belong to each product, I know it's going to be another join, but I need it so if more than 1 category belongs to a product to put it in the same column, and join them with a @ symbol, and its not the id's of the category, its the path, so I need to look up the category ID to another table to get the path.

So "category1/subcategory@category2" for example..

Thanks for any guidance.

EDIT: I still need to get the results merged as I am getting double the results I want, but I see a record for each category it's in with this..

Select zp.products_id as id, zpd.products_name as name, zcd.categories_name as categories, products_price_w as cost, products_price as price, zp.products_date_added as date_created, zp.products_image as thumbnail
FROM `zen_products` as zp
INNER JOIN `zen_products_description` as zpd ON zp.products_id = zpd.products_id
INNER JOIN `zen_products_to_categories`as zptc ON zp.products_id = zptc.products_id
INNER JOIN `zen_categories_description` as zcd on zptc.categories_id = zcd.categories_id
WHERE zp.products_status = 1
ORDER BY zp.products_id ASC;
Was it helpful?

Solution

What you are looking for is group_concat(). I think it would be something like this:

Select zp.products_id as id, zpd.products_name as name,
       group_concat(zcd.categories_name separator '@') as categories,
       products_price_w as cost, products_price as price,
       zp.products_date_added as date_created, zp.products_image as thumbnail
FROM `zen_products` as zp
INNER JOIN `zen_products_description` as zpd ON zp.products_id = zpd.products_id
INNER JOIN `zen_products_to_categories`as zptc ON zp.products_id = zptc.products_id
INNER JOIN `zen_categories_description` as zcd on zptc.categories_id = zcd.categories_id
WHERE zp.products_status = 1
group by zp.products_id
ORDER BY zp.products_id ASC;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top