要獲得每個問題的問題和選擇:
SELECT question, choice_text
FROM questions
JOIN choices
ON questions.question_id = choices.question_id
添加之前LEFT JOIN,如果你也想的是沒得選擇的問題。
要獲得計數每個答案你可以這樣做:
SELECT question, choice_text, COUNT(answers.choice_id)
FROM questions
JOIN choices
ON questions.question_id = choices.question_id
LEFT JOIN answers
ON questions.question_id = answers.question_id
AND choices.choice_id = answers.choice_id
GROUP BY questions.question_id, choices.choice_id
ORDER BY questions.question_id, choices.choice_id
要得到的是選擇的每一個答案(每題),請使用以下查詢百分比人數:
SELECT question, choice_text, COUNT(answers.choice_id) * 100/questiontotal
FROM questions
JOIN (
SELECT questions.question_id, COUNT(answers.choice_id) AS questiontotal
FROM questions
LEFT JOIN answers ON questions.question_id = answers.question_id
GROUP BY questions.question_id
) AS answercounts
ON questions.question_id = answercounts.question_id
JOIN choices ON questions.question_id = choices.question_id
LEFT JOIN answers
ON questions.question_id = answers.question_id
AND choices.choice_id = answers.choice_id
GROUP BY questions.question_id, choices.choice_id
ORDER BY questions.question_id, choices.choice_id;
下面是我用TESTDATA:
CREATE TABLE questions (question_id int, question nvarchar(100));
INSERT INTO questions (question_id, question) VALUES
(1, 'Foo?'),
(2, 'Bar?');
CREATE TABLE choices (choice_id int, question_id int, choice_text nvarchar(100));
INSERT INTO choices (choice_id, question_id, choice_text) VALUES
(1, 1, 'Foo1'),
(2, 1, 'Foo2'),
(3, 1, 'Foo3'),
(4, 2, 'Bar1'),
(5, 2, 'Bar2');
CREATE TABLE answers (answer_id int, question_id int, choice_id int);
INSERT INTO answers (answer_id, question_id, choice_id) VALUES
(1, 1, 1),
(2, 1, 1),
(3, 1, 3),
(4, 2, 4),
(4, 2, 5);
和輸出我上次查詢得到對這個數據:
'Foo?', 'Foo1', 66.6667
'Foo?', 'Foo2', 0.0000
'Foo?', 'Foo3', 33.3333
'Bar?', 'Bar1', 50.0000
'Bar?', 'Bar2', 50.0000
在你的問題的更新中,你說你想返回一個問題的所有值在一行上。我會建議你做而不是嘗試做到這一點,而是使用我給你上面的方法。如果您需要向最終用戶提供一行數據,則可以使用PHP完成。
你只是想要chocies,還是計數?什麼是你的「其他問題」,你想做什麼「數學」? – 2010-01-22 22:46:51
您沒有在尋找任何關於正確答案的信息?只是問題/選擇的可能性? – 2010-01-22 22:49:47
@Evan:這是一項調查,而不是測試 - 沒有正確的答案。 – Martha 2010-01-22 22:51:41