2013-02-11 75 views
1

我有两个表这样包括在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       | 
+---------+------------+--------------------+ 

回答

0

看起来像你缺少你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 

我也改变了自己的加入,使profile_answers表你的主桌。

祝你好运。

+0

但是,然后,添加group_by导致此查询的执行时间很长。其中约4000秒的记录约为15秒 – 2013-02-11 20:37:00

+0

@ManjunathManohar - 您可以尝试关闭它,但我认为这是GROUP_CONCAT需要的。 – sgeddes 2013-02-11 20:38:19

+0

http://dpaste.com/919899/。在这个查询花了15秒 – 2013-02-11 20:40:33

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;