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 | [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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With