SQL查询 - 分组依据不起作用

时间:2011-11-29 19:07:16

标签: mysql sql

我有一个像这样的表“答案”:

Id, Registration_id, attendee_id, question_id, answer
12   Reg02                1             1        Paul
13   Reg02                1             2        Smith
14   Reg03                2             1        Rachel
15   Reg03                2             2        Silva

我的查询是:

Select attendee_id, answer
From wp_events_answer;                            

结果我得到了这个:

attendee_id  answer
    1         Paul
    1         Smith
    2         Rachel      
    2         Silva

但是我想要这个:

 attendee_id  FirstName   Name
    1         Paul        Smith
    2         Rachel      Silva  

我添加了Group By attendee_id。但它仍然无效。因此,它只显示:

 attendee_id    FirstName
 1              Paul
 2              Rachel

你能告诉我出了什么问题吗?

由于

3 个答案:

答案 0 :(得分:5)

你不需要一个团体,你需要一个自我加入。

SELECT f.attendee_id, f.answer as FirstName, l.answer as Name
FROM wp_events_answer f
    JOIN wp_events_answer l ON f.attendee_id = l.attendee_id
WHERE f.question_id = 1 AND l.question_id = 2

答案 1 :(得分:2)

如果您需要从表中显示多行以显示在结果中,则需要将表连接到自身。

select fn.attendee_id, fn.answer as FirstName, ln.answer as lastName FROM  wp_events_answer as fn INNER JOIN wp_events_answer as ln WHERE (fn.attendee_id = ln.attendee_id) and (fn.question_id = 1) and (ln.question_id=2)

答案 2 :(得分:0)

我认为您正在寻找GROUP_CONCAT

select 
  attendee_id, 
  group_concat(answer ORDER BY Id
               SEPERATOR ' ')
from wp_events_answer
group by attendee_id