2013-03-12 28 views
0

我在MySQL中有三个表:application,questionsquestions_answer如何从多态MySQL表中检索数据

applicationuser_id; questions商店question_idtype of questions(即名称,身份证,学校名称); questions_answer存储参考user_idquestion_idanswers

据我所知,这种类型的关联称为多态关联。现在我迷失了如何从不同的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 

回答

0

你需要的是一个PIVOT型功能,MySQL不支持PIVOT如SQL Server或Oracle。您可以使用下面的脚本使用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 DEMO

+0

我一直对'declare'越来越语法错误,实现pivot。它需要额外的语法才能工作吗? – Khairul 2013-03-12 08:18:36

+0

删除声明并尝试 – 2013-03-12 21:19:11

+0

仍然收到相同的消息:'你的SQL语法错误;检查对应于你的MySQL服务器版本的手册...' – Khairul 2013-03-13 09:21:28