2013-03-12 52 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