I asked a question yesterday about using MySQL to tally results to a survey.
Now my question is, if I had a table of survey questions, a table of survey choices, and a table of users answers to those survey questions, how would I select the survey question along with all the choices for that survey within the same query?
Questions Table
question_id (int)
question (text)
Choices Table
choice_id (int)
question_id (int)
choice_text (varchar)
Answers Table
answer_id (int)
question_id (int)
choice_id (int)
What SELECT should I do to get the survey question along with all the choices for that survey (known or unknown amount) all in the same query? (if possible, also do the math, found in my other question, within the same query)
I’m not so advanced with MySQL.
Thanks
EDIT:
Sorry, What I meant was, I’m trying to get a SELECT statement to select the question, and all the choices corresponding to that question, in one row.
If I do something like
SELECT question_id, question, choice_id, choice_text FROM questions LEFT JOIN choices USING(question_id)
I get multiple rows, one for each choice_id.
The results should be something like
question choice_1 choice_2 choice_3
A or B or C A B C
The math part is tallying up the results to the survey, and yes, the choice_id is a PK, if that helps.
To get the questions and the choices for each question:
Add LEFT before JOIN if you also want questions that have no choices.
To get the counts for each answer you could do this:
To get the number of people that selected each answer as a percentage (per question) use the following query:
Here’s the testdata I used:
And the output I get with the last query on this data:
In the update to your question you say you want to return all the values for one question on one row. I would recommend that you do not try to do this, and instead use the method I have given you above. If you need to present the data in one row to your end-user, this can be done using PHP.