我正在尝试使用php和sql创建一个简单的轮询函数。 我有三张桌子:
问题
其中只包含提出的每个问题
question_id | question_text | created_at
答案
其中包含每个问题的每个答案
question_id | answer_id | ANSWER_TEXT
已回答的问题
为每个选项投票的记录
question_id | answer_id | user_ip
我正在尝试编写一个查询,它将返回一个问题(最新的)以及该问题的所有可能答案,最后是每个问题的每个答案的计数。我知道我将不得不使用GROUP BY子句和可能的LEFT OUTER JOIN,但确切的语法是让我无法理解。
任何建议都将不胜感激。感谢。
答案 0 :(得分:2)
这与本文http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/中的逻辑非常相似。
基本上你需要一个子查询来选择你感兴趣的单个记录/问题,以及一个外部查询来选择你感兴趣的那个记录相关的信息
(我可以发布另一个SQL语句添加到已经发布的好集合中,但我想我会试着解释其他发布的查询是如何工作的)
答案 1 :(得分:1)
假设您正在使用MySQL
:
SELECT q.* ,
(
SELECT COUNT(*)
FROM answered_questions aq
WHERE aq.answer_id = a.answer_id
AND aq.question_id = q.question_id
) AS votes
FROM (
SELECT *
FROM question
ORDER BY
created_at DESC
LIMIT 1
) q
LEFT OUTER JOIN
answers a
ON a.question_id = q.question_id
答案 2 :(得分:1)
此查询应适用于大多数DBMS:
select q.question_id, question_text, a.answer_id, a.answer_text, count(user_ip)
from questions q
inner join answers a on (q.question_id = a.question_id)
left join answered_questions aq on (a.question_id = aq.question_id
and a.answer_id = aq.answer_id)
where created_at = (select max(created_at)
from questions
)
group by q.question_id, a.answer_id, q.question_text, a.answer_text
答案 3 :(得分:0)
SELECT
questions.question_id,
questions.question_text,
answers.answer_id,
answers.answer_text,
COUNT(answered_questions.user_ip)
FROM
questions,answers,
answered_questions
WHERE
questions.question_id=answers.question_id
AND
questions.question_id=
(SELECT
question_id
FROM questions
ORDER BY questions.created_at
LIMIT 1
)
AND
answered_questions.question_id=questions.question_id
GROUP BY
questions.question_id
应该有用(虽然我没有测试过)。