我在mysql数据库中有3个表:
-questions(id,content)
-answers(id,content,question)其中问题是外键,告诉我们答案涉及哪个问题
-survey(survey_id,answer)其中survey_id对于参与调查的一个人来说是唯一的,答案表明了他给出的答案。
现在我想写一个查询,它会显示一个表格,其中包含参与调查的人员的ID以及他在不同栏目中给出的所有答案。
这是我的疑问:
select survey.survey_id,
CASE WHEN answers.question = 1
then answers.content
end
as 'Question 1',
CASE WHEN answers.question = 2
then answers.content
end
as 'Question 2'
from survey inner join answers on survey.answer_id = answers.id;
这样做的正确方法是什么?
答案 0 :(得分:1)
你可以使用(假的)聚合函数来减少行,例如:
select survey.survey_id,
max(CASE WHEN answers.question = 1
then answers.content
end) as 'Question 1',
max(CASE WHEN answers.question = 2
then answers.content
end) as 'Question 2'
from survey inner join answers on survey.answer_id = answers.id
group by survey.survey_id
答案 1 :(得分:1)
使用条件聚合:
select s.survey_id,
max(case when a.question = 1 then a.content end) as Question_1,
max(case when a.question = 2 then a.content end) as Question_2
from survey s inner join
answers a
on s.answer_id = a.id
group by s.survey_id;
注意: