0

我在 MySQL 中有三个表:applicationquestionsquestions_answer.

application商店user_idquestions商店question_idtype of questions(即姓名、身份证、学校名称);questions_answer存储对和的answers引用。user_idquestion_id

据我了解,这种类型的关联称为多态关联。现在我不知道如何从不同的 question_id 检索数据并将它们作为列标题。

我希望这是有道理的。

编辑:

为了说明,以下是相应的表格:

application

user_id         name
-------------------------------
100             Leon Barnacles
101             Richard Kennard
102             Fareeza Salleh

questions

question_id     question_name
---------------------------------------------   
20              NRIC
21              Have you ever applied to TFM?
22              What's your current GPA?
23              Name of school

questions_answer

question_id     user_id     answer
------------------------------------------------
20              100         880808-06-8990
20              100         900990-14-0911
23              102         SMK Taman Pandamaran

我希望检索的内容:

Name                NRIC                Name of school
------------------------------------------------------------
Leon Barnacles      880808-06-8990      
Richard Kennard     900990-14-0911
Fareeza Salleh                          SMK Taman Pandamaran
4

1 回答 1

0

你需要的是一个PIVOT类型函数,MYSQL 不像 SQL Server 或 Oracle 那样支持 PIVOT。您可以使用以下脚本来实现对问题表数据的pivot使用max and case

select group_concat(concat('max(case when question_id = ''', question_id, ''' then
             answer end) as `', question_name ,'`')) into @sql from tfm_questions;

set @sql = 
concat('select full_name, ', @sql, ' from 
          (
             select a.full_name, q.question_name, an.answer, q.question_id
             from tfm_application a
             inner join tfm_questions_answer an on a.user_id = an.user_id
             inner join tfm_questions q on an.question_id = q.question_id
          ) x
       group by full_name');


select @sql;

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SQL 演示

于 2013-03-12T04:55:38.753 回答