我需要创建一条 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
关于php - MySQL 将多行连接成一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26804258/