开发者

Rows with null value for group_concat not returned

I've got the following MySQL query that's supposed to return records from table a and b (one to many relationship), and also a comma seperated list of any values returned from table c. However, there won't always be records in table c (which is why I'm using a LEFT OUTER JOIN to join it to table a).

SELECT  `a`.`id` , `a`.`name` , `b`.`id` AS  `b_id` , `b`.`name` AS  `b_name` , GROUP_CONCAT(  `c`.`l_id` ) AS  `c_ls`
FROM  `a`
INNER JOIN  `b` ON  `a`.`b_id` =  `b`.`id`
LEFT OUTER JOIN  `c` ON  `a`.`id` = `c`.`a_id`
GROUP BY `a`.`id`
ORDER BY  `a`.`created` DESC

The query above returns 1 record when it should return 2. Record 1 has 3 matching records in table c, record 2 has 0 matching records in table c.

The query returns:

id | name | b_id | b_name | c_ls
1  | John |   2  |  Bla   | [BLOB - 3 B]

If I remove the GROUP_CONCAT and GROUP_BY clauses then it returns 2 records:

id | name | b_id | b_name | c_ls
1  | John |   2  |  Bla   |开发者_StackOverflow中文版 [BLOB - 3 B]
2  | Fred |   3  |  Blo   | [BLOB - NULL]

It seems that if c_ls is null then GROUP_CONCAT stops the row from being returned. Any thoughts as to what I'm doing wrong?


The answer previously marked as right is unfortunately wrong (as user desaivv noted in the comment).

It must read IFNULL, [not ISNULL, isnull just takes one parameter and returns a boolean] !

IFNULL returns the second paramter if null:

SELECT  `a`.`id` , `a`.`name` , `b`.`id` AS  `b_id` , `b`.`name` AS  `b_name` ,   
IFNULL(GROUP_CONCAT(  `c`.`l_id` ), '') AS  `c_ls`
FROM  `a`
INNER JOIN  `b` ON  `a`.`b_id` =  `b`.`id`
LEFT OUTER JOIN  `c` ON  `a`.`id` = `c`.`a_id`
GROUP BY `a`.`id`
ORDER BY  `a`.`created` DESC

But this is not the solution at all! What we need is a "convoluted" join -

So please check this SQL Fiddle: http://www.sqlfiddle.com/#!2/54c6f/3/0


Try to use LEFT JOIN instead of INNER JOIN


Try this -

SELECT  `a`.`id` , `a`.`name` , `b`.`id` AS  `b_id` , `b`.`name` AS  `b_name` , ISNULL(GROUP_CONCAT(  `c`.`l_id` ), '') AS  `c_ls`
FROM  `a`
INNER JOIN  `b` ON  `a`.`b_id` =  `b`.`id`
LEFT OUTER JOIN  `c` ON  `a`.`id` = `c`.`a_id`
GROUP BY `a`.`id`
ORDER BY  `a`.`created` DESC

Added ISNULL to check if Group_concat is null and return blank instead of NULL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜