[英]How to join two tables but not to repeat rows in mysql
I am facing one issue for getting data.我正面临一个获取数据的问题。 I am new in Mysql.
我是 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.实际上我正在使用 join 但是当我使用 join 时,由于连接两个表是连接的实际行为,因此行会重复。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.