[英]MySQL join multiple rows into one column
I need to create an SQL statement to join multiple rows into one column. 我需要创建一条SQL语句以将多行连接到一列中。 I have three table which are shown below. 我有三个表,如下所示。 I need to join them all to get 1 row for each product (ie group by products.id). 我需要将它们全部加入才能为每个产品获得1行(即,按products.id分组)。
There can be up to 6 images per product in the products_images table. 在products_images表中,每个产品最多可以有6张图像。 I need a column for each image even if there are no product images. 即使没有产品图片,我也需要为每个图片添加一列。
Products Table
---
id
product_name
supplier_id
Suppliers Table
---
id
company_name
Product Images Table
---
id
product_id
fullsize
Here is an example dump of what i'm trying to achieve: 这是我要实现的示例转储:
id product_name company_name image1 image2 image3 image4 image5 image6
1 Ballpoint pen Impression img/1.jpg img/2.jpg img/3.jpg img/4.jpg img/5.jpg null
2 T-shirt Impression img/6.jpg img/7.jpg img/8.jpg null null null
3 Jumper Impression null null null null null null
As you can see the first product has 5 images, second product has 3 and last product has 0 images. 如您所见,第一个产品有5张图像,第二个产品有3张图像,最后一个产品有0张图像。
How can I achieve the above result? 如何获得以上结果?
Thanks! 谢谢!
You need to look into using CASE statements. 您需要研究使用CASE语句。
For instance. 例如。
SELECT id,
product_name,
company_name,
CASE WHEN Product Images Table.id = 1 THEN image1 ELSE NULL END AS image1,
CASE WHEN Product Images Table.id = 2 THEN image1 ELSE NULL END AS image2
....
FROM Products Table
JOIN Suppliers Table
JOIN Product Images Table
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.