我在MySQL中有三个表:application
,questions
和questions_answer
。
application
存储user_id
; questions
存储question_id
和type of questions
(即姓名,身份证,学校名称); questions_answer
存储引用answers
和user_id
的{{1}}。
据我所知,这种类型的关联称为多态关联。现在我迷失了如何从不同的question_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
答案 0 :(得分: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;