2017-04-06 39 views
0

我有以下兩個表:想不通這有什麼錯我的GROUP_CONCAT

Table `Products` 
ProductId (INT) PrimaryKey 
Name  (VARCHAR(25)) 
Description (VARCHAR(255)) 

Table `Images` 
ImageId   (INT) PrimaryKey 
ImagePath   (VARCHAR(255)) 
ImageDescription (VARCHAR(255)) 
products_ProductId (INT) 

Images表包含關聯到具體產品的圖片。它與Products表格有一對多的關係,所以產品可以有多個圖像。唯一可以爲空的列(並且在當前大部分情況下)是Images.ImageDescription。我想選擇產品列表,並在同一查詢中獲取所有圖片。我寫了下面的查詢:

SELECT P.*, 
     GROUP_CONCAT(DISTINCT CONCAT(I.ImagePath, '@', I.ImageDescription) SEPARATOR ',') AS _ProductImages 
FROM (SELECT * FROM Products WHERE ProductId IN (1,2,3,4,5,6,7)) as P 
LEFT JOIN Images as I ON I.products_ProductId = P.ProductId 
GROUP BY P.ProductId 

所有選定的產品已在圖像表中的至少1相關的行,第一個3在影像表3個相關的行,然而,運行查詢時,和它返回,_ProductImages在每一行都是NULL。有人能指出我做錯了什麼嗎?

+0

當你改變你的'LEFT JOIN'到'INNER JOIN'會發生什麼? – Psi

+1

「圖像」記錄中「ImagePath」和/或「ImageDescription」是否爲空? –

+0

@Thorsten Kettner我編輯了這篇文章,並且給你的問題添加了答案。在大多數當前的測試用例中,ImageDescription可以爲null,並且它爲空。 –

回答

1

當您用NULL連接字符串時,結果爲NULL。因此:

CONCAT(I.ImagePath, '@', COALESCE(I.ImageDescription, '')) 
+0

是的,這解決了它,謝謝!將在幾分鐘內接受它:) –

2

除了托爾斯滕的回答是:

相反的CONCAT()你也可以使用CONCAT_WS()。詳細瞭解它here

它適用於NULL值並省略不必要的分隔符。

例子:

mysql > select concat('whatever', '@', NULL); 
+-------------------------------+ 
| concat('whatever', '@', NULL) | 
+-------------------------------+ 
| NULL       | 
+-------------------------------+ 
1 row in set (0.00 sec) 

mysql > select concat_ws('@', 'whatever', NULL); 
+----------------------------------+ 
| concat_ws('@', 'whatever', NULL) | 
+----------------------------------+ 
| whatever       | 
+----------------------------------+ 
1 row in set (0.00 sec) 

mysql > select concat_ws('@', 'whatever', 'whatever'); 
+----------------------------------------+ 
| concat_ws('@', 'whatever', 'whatever') | 
+----------------------------------------+ 
| [email protected]      | 
+----------------------------------------+ 
1 row in set (0.00 sec) 

隨着托爾斯滕的答案,你會得到:

mysql > select concat('whatever', '@', COALESCE(NULL, '')); 
+---------------------------------------------+ 
| concat('whatever', '@', COALESCE(NULL, '')) | 
+---------------------------------------------+ 
| [email protected]         | 
+---------------------------------------------+ 
1 row in set (0.00 sec) 
相關問題