MySQL根据条件多次选择进入列

MySQL根据条件多次选择进入列,mysql,sql,select,Mysql,Sql,Select,我在mysql数据库中有3个表: -问题(id、内容) -答案(id、内容、问题),其中问题是一个外键,告诉我们答案与哪个问题相关 -调查(调查id,答案),其中调查id对于接受调查的人是唯一的,并且答案表示他给出的答案 现在我想写一个查询,向我显示一个表,其中包含接受调查的人的Id以及他在不同列中给出的所有答案 这是我的疑问: select survey.survey_id, CASE WHEN answers.question = 1 then answers.conten

我在mysql数据库中有3个表:

-问题(id、内容)

-答案(id、内容、问题),其中问题是一个外键,告诉我们答案与哪个问题相关

-调查(调查id,答案),其中调查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;
但我不认为这是一种方式,我得到了图片上显示的内容(带空值)

现在我想得到的是:

正确的方法是什么?

您可以使用(假)聚合函数来减少行数,例如:

  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 

使用条件聚合:

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;
注:

  • 所有表都有别名
  • 所有列都是限定的,这意味着它们明确地指定了它们来自的表
  • 仅对字符串和日期常量使用单引号。不要对表别名使用单引号

每个调查id只有两个答案??