无法弄清楚我的GROUP_CONCAT有什么问题

时间:2017-04-06 11:27:28

标签: mysql

我有以下两个表:

 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表格是一对多的关系,因此产品可以有多个图像。唯一可以为null的列(当前大部分情况都是如此)是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

所有选定的产品在Images表中至少有一个关联的行,而前三个在Images表中有3个关联的行,但是,当查询运行时,它返回,_ProductImages为NULL在每一行。有人可以指出我做错了什么吗?

2 个答案:

答案 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') |
+----------------------------------------+
| whatever@whatever                      |
+----------------------------------------+
1 row in set (0.00 sec)

根据Thorsten的回答,你会得到:

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

答案 1 :(得分:1)

将字符串与NULL连接时,结果为NULL。因此:

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