To ask questions and options for each question:
SELECT question, choice_text FROM questions JOIN choices ON questions.question_id = choices.question_id
Add LEFT before JOIN if you also want to ask questions that have no choice.
To get the counts for each answer, you can do this:
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
To get the number of people who chose each answer as a percentage (per question), use the following query:
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;
Here are the tests I used:
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);
And the output that I get with the last request for this data:
'Foo?', 'Foo1', 66.6667 'Foo?', 'Foo2', 0.0000 'Foo?', 'Foo3', 33.3333 'Bar?', 'Bar1', 50.0000 'Bar?', 'Bar2', 50.0000
In updating your question, you say that you want to return all the values โโfor one question on one line. I would recommend that you not try to do this, but instead use the method that I gave you above. If you need to present data in one line to the end user, this can be done using PHP.