I am facing one issue for getting data. I am new in Mysql. Firstly i will show my table structure
order_products
id user_id product_id product_name
1 1 10 Jacket1
2 1 10 Jacket2
order_products_sizes
id order_product_id size qty
1 1 S 56
2 1 M 36
3 1 XL 36
4 1 2XL 56
5 2 S 32
6 2 M 28
7 2 XL 28
8 2 2XL 32
9 2 3XL 69
My expected Output:-
product_name S M XL 2XL 3XL
JACKET1 56 36 36 56
JACKET2 32 28 28 32 69
for first row 3xl would be empty beacuse there is no size available in order_product_sizes
Actually i am using join but when i use join the rows are repeating because of joining two table that is actual behavior of joins. I have tries so far:-
SELECT order_products.product_name,
CASE
WHEN order_product_sizes.order_product_id = order_products.id AND
order_product_sizes.size = 'L' THEN order_product_sizes.qty
END AS L
from order_products
join
order_product_sizes
on order_products_sizes.order_product_id = order_products.id;
You can try below - using conditional aggregation
SELECT order_products.product_name,
max(CASE
WHEN
order_product_sizes.size = 'S' THEN order_product_sizes.qty
END) AS S,
max(CASE
WHEN
order_product_sizes.size = 'M' THEN order_product_sizes.qty
END) AS M,
max(CASE
WHEN
order_product_sizes.size = 'XL' THEN order_product_sizes.qty
END) AS XL,
max(CASE
WHEN
order_product_sizes.size = '2XL' THEN order_product_sizes.qty
END) AS '2XL',
max(CASE
WHEN
order_product_sizes.size = '3XL' THEN order_product_sizes.qty
END) AS '3XL'
from order_products join order_products_sizes
on order_products_sizes.order_product_id = order_products.id
group by order_products_sizes.order_product_id
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.