我需要创建一个SQL语句,将多行连接到一列中。我有三张表,如下所示。我需要加入他们所有人,为每个产品获得1行(即按products.id分组)。
products_images表中的每个产品最多可以有6个图像。即使没有产品图像,我也需要为每个图像创建一个列。
Products Table
---
id
product_name
supplier_id
Suppliers Table
---
id
company_name
Product Images Table
---
id
product_id
fullsize
以下是我试图实现的一个转储示例:
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
正如您所看到的,第一个产品有5个图像,第二个产品有3个,最后一个产品有0个图像。
我如何才能达到上述结果?
谢谢!
您需要研究如何使用CASE语句。
例如。
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