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 |
+---------+------------+--------------------+
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;
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.
来源:https://stackoverflow.com/questions/14820298/include-null-results-in-group-concat