在group_concat中显示空记录

时间:2013-02-11 20:32:14

标签: mysql performance group-concat

我有两张这样的表

profile_answers

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

的教育

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

我运行了查询,

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

我得到了

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

我其实想要,

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

我试过,ISNULL,IFNULL和group_by profile_answers.id的组合,这给了我正确的结果,但就运行时间而言,结果相当昂贵

1 个答案:

答案 0 :(得分:2)

这是我在上一个问题中的回答......

看起来你错过了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

我还改变了你的JOIN,使profile_answers表成为主表。

祝你好运。