Manjunath Manoharan
Manjunath Manoharan

Reputation: 4617

Include null results in group_concat

I have two tables like this

profile_answers

+---------+------------+
|      id | class_name |
+---------+------------+
|       1 | Class 1    |
|       2 | Class 2    |
|       3 | Class 1    |
+---------+------------+

educations

+---------+--------------------+------------+
|      id | profile_answers_id |  sample    |
+---------+--------------------+------------+
|       1 | 1                  |     1234   |
|       2 | 1                  |     2334   |
|       3 | 1                  |     3434   |
+---------+------------+--------------------+

I ran the query,

select educations.profile_answer_id, GROUP_CONCAT(educations.sample) from educations
LEFT JOIN profile_answers ON educations.profile_answers_id = profile_answers.id

I got

+--------+--------------------+-------------+
|      id | sample                          | 
+---------+--------------------+------------+
|       1 | 1234,2334,3434                  |
+---------+------------+--------------------+

I actually want,

+--------+--------------------+-------------+
|      id | sample                          | 
+---------+--------------------+------------+
|       1 | 1234,2334,3434                  |
|       2 | NULL                            |
|       3 | NULL                            |  
+---------+------------+--------------------+

Upvotes: 2

Views: 1854

Answers (2)

RolandoMySQLDBA
RolandoMySQLDBA

Reputation: 44343

SELECT id,IFNULL(samples,'NULL') sample FROM 
(
    SELECT
        AA.id,
        GROUP_CONCAT(DISTINCT BB.sample) samples
    FROM
        profile_answers AA LEFT JOIN educations BB
        ON AA.id = BB.profile_answers_id
    GROUP BY AA.id
) A;

Upvotes: 3

sgeddes
sgeddes

Reputation: 62841

Looks like you're missing your GROUP BY:

select profile_answers.id, GROUP_CONCAT(educations.sample) 
from profile_answers
LEFT JOIN educations ON educations.profile_answers_id = profile_answers.id
GROUP BY profile_answers.id

I also altered your JOIN to make the profile_answers table your main table.

Good luck.

Upvotes: 0

Related Questions