簡體   English   中英

MySQL將多行合並為一列

[英]MySQL join multiple rows into one column

我需要創建一條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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM