Mysql选择动态行值作为表中的列名和来自另一个表的值

时间:2017-05-14 09:01:10

标签: mysql sql

我安排了一项调查,项目有一些问题。用户必须从公众收集给定的项目答案。调查表如

用户表

user_id     user_name
  1          User 1   
  2          User 2

项目表

project_id  project_name
  1           project 1    
  2           project 2

问题表

ques_id  project_id  ques_name
  1         1         Question 1
  2         1         Question 2 
  3         1         Question 3
  4         1         Question 4 

答案表

ans_id  public_id  user_id ques_id  ques_ans
  1         1      1         1     Answer 1
  2         1      1         2     Answer 2 
  3         1      1         3     Answer 3
  4         1      1         4     Answer 4 

现在我想生成一个报告,其中问题表值作为列名与给定的project_id匹配,并将问题答案作为与ques_id匹配的答案表的值

而且,她是我预期的输出:

User_Name  public_id  Question 1  Question 2  Question 3  ...
User 1        1         Answer 1   Answer 2    Answer 3   ...

有人建议使用数据透视,但我发现" MySQL并没有原生支持旋转操作"谁能帮助我?

3 个答案:

答案 0 :(得分:1)

您可以使用查询的其他输出格式。例如:

SELECT user_name, answer.project_id, ques_name, ques_ans
FROM 
    `answer` 
    INNER JOIN `user` USING (user_id)
    INNER JOIN `question` USING (ques_id);

按特定项目限制行添加WHERE子句:

 WHERE project_id = @ProjectID

然后使用PHP 将结果转换为所需的视图 如果使用MySQL解决问题至关重要,那么使用aliaces手动创建新的colums。要按用户和项目聚合行,请使用GROUP BY子句。要显示可能的非空值,请使用MAX()函数。在你的情况下:

SELECT
  user_name, project_id,
  MAX(IF(ques_name = 'Question 1', ques_ans, NULL)) AS `Question 1`,
  MAX(IF(ques_name = 'Question 2', ques_ans, NULL)) AS `Question 2`,
  MAX(IF(ques_name = 'Question 3', ques_ans, NULL)) AS `Question 3`,
  MAX(IF(ques_name = 'Question 4', ques_ans, NULL)) AS `Question 4`
FROM
    (SELECT 
        ans_id, user_id, user_name, answer.project_id, ques_name, ques_ans
    FROM 
        answer
        INNER JOIN `user` USING (user_id)
        INNER JOIN question USING (ques_id)
        ) AS tmp
GROUP BY
  user_id, project_id;

答案 1 :(得分:0)

您的查询应该是:

SELECT an.user_name,an.public_id,qs.quest_name,an.quest_answer 
FROM answer_table an,question_table qs,user_table usr
WHERE an.quest_id = qs.quest_id
AND an.user_id=usr.user_id

对于表格轮换:这里有一个关于旋转表格的类似问题

mysql pivot table date (vertical to horizontal data)

答案 2 :(得分:0)

最后代码正在运行

SET @sql = NULL;
    SELECT
    GROUP_CONCAT(DISTINCT
    CONCAT(
    'MAX(IF(a.ques_id = ',
    ques_id,
    ', a.ques_ans, NULL)) AS `',
    ques_name,'`'
    )
    ) INTO @sql
     FROM survey_answer inner join survey_question on  survey_answer.ques_id=survey_question.id;

set @sql = CONCAT('select u.user_name ,q.category_id,a.p_code, ' ,@sql,'  FROM `survey_answer` as a
LEFT JOIN `users` as u ON a.user_id = u.user_id
LEFT JOIN `survey_question` as q ON a.ques_id= q.id');
 PREPARE stmt FROM @sql;
 EXECUTE stmt;
 DEALLOCATE PREPARE stmt;