如何编写这个mysql查询?

时间:2011-07-06 10:54:44

标签: php mysql sql

我有三张桌子tb_poll,tb_poll_answer,tb_poll_votes

tb_poll id,question

tb_poll_answer id,poll_id,answer

tb_poll_votes id,poll_answer_id

我想选择所有问题并回答(计票)。

最后我想列出

Id    Question           Answers

1     Which is....?     1.PHP(70) 2.ASP(30) 3.JSP(2)

2     ......             .......   

如何在这里编写最好的mysql查询?

2 个答案:

答案 0 :(得分:2)

立即尝试此查询:

 SELECT q.id,q.question,
       GROUP_CONCAT(CONCAT(a.id,'.',a.answer,COUNT(v.id) SEPARATOR ' ')) AS `Answers`
 FROM `tb_poll` AS q
 LEFT JOIN `tb_poll_answers` AS a
  ON q.id = a.poll_id
 LEFT JOIN `tb_poll_votes` AS v
  ON a.id = v.poll_answer_id
 WHERE 1
 GROUP BY q.id
 ORDER BY q.id

答案 1 :(得分:0)

最后我通过子查询得到了结果

 SELECT q.id,q.question,av.vt,GROUP_CONCAT(CONCAT(av.answer,av.vt) SEPARATOR ' ') 
 AS Answers FROM tb_poll AS q LEFT JOIN
 (SELECT a.answer,a.poll_id,COUNT(v.id) AS vt FROM tb_poll_answers AS a LEFT JOIN tb_poll_votes AS v ON a.id=v.poll_answer_id GROUP BY a.id) AS av
ON q.id=av.poll_id
GROUP BY q.id