Include null results in group_concat

帅比萌擦擦* 提交于 2019-12-20 03:37:13

问题


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                            |  
+---------+------------+--------------------+

回答1:


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;



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!