這些都是我的表:SQL視圖查詢不能
portal_users(id, first_name, last_name, email, ...,)
courses(id, name, location, capacity, ...,)
feedback_questions(id, question, ...,)
feedback_answers(id, answers, IDquestion, IDuser, IDcourse)
我想要做這樣的觀點:
course | first_name | last_name | IDuser | IDcourse | question_1 | answer_1 | question_2 | answer_2
到目前爲止
CREATE VIEW feedback_answers_vw
as
SELECT
fa.id,
fa.answer,
fq.question,
pu.first_name,
pu.last_name,
fa.IDuser,
fa.IDcourse
FROM feedback_answers fa
INNER JOIN feedback_questions fq
ON fa.IDquestion = fq.id
INNER JOIN portal_users pu
ON fa.IDuser = pu.id
INNER JOIN courses cu
on fa.IDcourse = cu.id
GROUP BY
fa.IDcourse, fa.IDuser
這只是顯示一個問題及其答案,但不是屬於同一課程和用戶的所有問題。
我可以在SELECT語句
SELECT
fa.id,
(select question
from feedback_questions
where id = 1) as question_1,
(select question
from feedback_questions
where id = 2) as question_2,
(select question
from feedback_questions
where id = 3) as question_3,
pu.first_name,
pu.last_name,
fa.IDuser,
fa.IDcourse
像這樣的東西硬編碼,但我想這樣做的正確的方式,所以我不會改變被添加了問題的代碼每次。
編輯: 這是我的表的數據例如:
**Portal users:**
1, tom, hanks, [email protected], ...,
2, steven, spielberg, [email protected], ...,
**Courses:**
1, quality, california, 30
2, information technologies, texas, 24
**Questions:**
1, How did you find the course?, ...,
2, Do you want purchase order?, ...,
**Answers:**
1, Internet, 1, 1, 1
2, yes, 2, 1, 1
3, TV, 1, 2, 1,
4, no, 2, 2, 1,
5, Internet, 1, 1, 2
6, yes, 1, 1, 2
這是數據的例子,我想在視圖中顯示:
course|first_name|last_name|IDuser|IDcourse|Question_1|Answer_1|Question_2|Answer_2
----------------------------------------------------------------------------------
quality | tom | hanks | 1 | 1 | How did you find the course? | Internet | Do you want purchase order? | yes
quality | steven | spielberg | 2 | 1 | How did you find the course? | TV | Do you want purchase order? | no
Information technologies | tom | hanks | 1 | 2 How did you find the course? | Internet | Do you want purchase order? | yes
顯示回答問題*問題數的用戶數。 I.E. 如果我有3問題和2個用戶回答。顯示6行。每個用戶 3行,行之間的差異是問題,答案 – Toquis
讓我確保我明白了,你想的問題和答案的清單得到顯示爲同一行中對每個問題的答案對列? – Andreas
也許如果你發佈一些樣本數據和你的預期結果,它會有所幫助。這聽起來越來越像你想旋轉桌子。 – Andreas