我有一个查询,从一个表中提取问题,从另一个表中提取答案.
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
虽然这有效但我不喜欢为每个答案添加额外的子查询(questions.answers
是一个逗号分隔的潜在答案字符串).它是可行的,但我敢肯定必须有更好的方法.主要的是,不同的问题有不同的答案数量.
有没有更好的方法来做到这一点,或者这是一种可接受的做事方式?我认为查询中的多个子选择将来可能会有(小)性能损失(不是我的性能测试).
如果它适用,我不希望每个问题有超过5个答案.
SELECT q.question, q.answers, SUM(a.answer = 1) AS ans1, SUM(a.answer = 2) AS ans2 FROM questions q LEFT OUTER JOIN answers a ON (q.id = a.question_id) WHERE q.id = 1 GROUP BY q.id;