查询确实选择并计算另一个表中的记录

时间:2012-10-09 22:02:26

标签: php sql

我一直在研究这个问题,我似乎无法找到有效实现这一目标的方法。

基本上我有一个表格可以存在问题,我有一个表格可以跟踪问题的答案以及与该答案相关的用户的用户信息。答案都是真或假,我想跟踪每个问题的总真或假答案。

因此,第一个查询是选择问题表中的所有记录。 第二个查询按questionID选择答案

我想创建一个同时完成所有这些操作的查询,我最近尝试过但没有成功的查询如下:

SELECT questions.*, count(answers.*) as total_answers FROM questions
LEFT OUTER JOIN
(
SELECT answers.* AS true FROM votes
WHERE answer = 1 AND questionID = THIS.ID
)

此查询不起作用,因为我无法执行另一个WHERE语句,指定我只想获取答案为1或0的记录(真或假答案都是二进制)。我没有在SQL中找到一个THIS选择器或类似的东西。我希望我已经足够清楚了。在我遇到这个问题之前,我以为我对查询非常了解。

非常感谢任何帮助

2 个答案:

答案 0 :(得分:1)

类似的东西(你的结构对我来说不太清楚,所以可能需要进行调整)

select 
  q.*, 
  count(a.*) as total_answers, 
  sum(case when a.answer = 1 then 1 else 0 end) as total_correct,
  sum(case when a.answer = 0 then 1 else 0 end) as total_false
FROM questions q
left join answers a on q.ID = a.questionID
group by q.ID

答案 1 :(得分:1)

参考拉斐尔提到的答案,这是另一种写作方式:

Select  Question.*
,   Sum(TrueAnswer.answer)
+   Sum(FalseAnswer.answer)     As  total_answers
,   Sum(TrueAnswer.answer)      As  total_TrueAnswer
,   Sum(FalseAnswer.answer)     As  total_FalseAnswer
    From    questions       As  Question
    Left    Outer   Join
        answers         As  TrueAnswer
    On  Question.ID     =   TrueAnswer.questionID
    And TrueAnswer.answer   =   1
    Left    Outer   Join
        answers         As  FalseAnswer
    On  Question.ID         =   FalseAnswer.questionID
    And FalseAnswer.answer  =   0
    Group   by  Question.ID