I have a query that pulls up questions from one table and answers from another.
SELECT
questions.question,
questions.answers,
(SELECT COUNT(answer) FROM answers WHERE question_id = 1 AND answer = 1
GROUP BY answer) as ans1,
(SELECT COUNT(answer) FROM answers WHERE question_id = 1 AND answer = 2
GROUP BY answer) as ans2
FROM questions
WHERE questions.id = 1
While this works I don't like the idea of adding an extra subquery for each answer (questions.answers
is a comma-seperated string of potential answers). It's do-able but I'm sure there must be a better way. The main thing is that different questions have different numbers of answers.
Is there a better way to do this or is this an acceptable way of doing things? I'd imagine multiple subselects in a query could have a (small) performance hit in the future (not that I'm performance testing yet).
If it's applicable I don't expect to have more than 5 answers per question.