2017-04-06 31 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) 
相关问题