I'm building a webshop that sells shoes. I'm trying to write a command that will show the quantity of each size for 1 specific sneaker.
This is my ER-diagram
Link to my ER-Diagram can be seen here: imgur.com/a/QHpid2p
I want to add the quantity (qty) to all the different sizes but everything I try doesn't seem to work.
SELECT sn.sneaker_id, sn.sneaker_name,
(CASE WHEN sn.gender = 0 THEN 'Women'
WHEN sn.gender = 1 THEN 'Men'
END) as gender,
sn.description, sn.price,
GROUP_CONCAT(si.size),
GROUP_CONCAT(DISTINCT(i.path)),
bn.brand_name
FROM sneakers sn JOIN
sizes si
ON si.sneaker_fk = sn.sneaker_id JOIN
images i
ON i.sneaker_fk = sn.sneaker_id JOIN
brand_names bn
ON bn.brand_name_id = sn.brand_name_fk
WHERE sn.sneaker_id = 1
This is my actual result:
sneaker_id : 1
sneaker_name : Air Max 97 Silver Bullet
gender : Men
description : anfaslknsaf
price : 1500
GROUP_CONCAT(sizes.size) : 41.0,43.0,44.0,45.5,46.0
GROUP_CONCAT(DISTINCT(images.path)): img
brand_name : nike
My desired output would be something like:
sneaker_id : 1
sneaker_name : Air Max 97 Silver Bullet
gender : Men
description : anfaslknsaf
price : 1500
GROUP_CONCAT(sizes.size) : [41.0, 10],[43.0, 5],[44.0, 8],[45.5, 7],[46.0,8]
GROUP_CONCAT(DISTINCT(images.path)): img
brand_name : nike
It is a good practice to aggregate by all the unaggregated columns in a GROUP BY
query.
GROUP_CONCAT()
accepts multiple arguments and concatenates them together. So, you can do:
SELECT sn.sneaker_id, sn.sneaker_name,
(CASE WHEN sn.gender = 0 THEN 'Women'
WHEN sn.gender = 1 THEN 'Men'
END) as gender,
sn.description, sn.price,
GROUP_CONCAT('[', si.size, ', ', si.qty, ']'),
GROUP_CONCAT(DISTINCT(i.path)),
bn.brand_name
FROM sneakers sn JOIN
sizes si
ON si.sneaker_fk = sn.sneaker_id JOIN
images i
ON i.sneaker_fk = sn.sneaker_id JOIN
brand_names bn
ON bn.brand_name_id = sn.brand_name_fk
WHERE sn.sneaker_id = 1
GROUP BY sn.sneaker_id, sn.sneaker_name, gender, sn.description, sn.price, bn.brand_name;
Note that you can remove the WHERE
clause and this will work for all sneaker ids.