-1

我一直在研究这个问题一段时间,但我似乎无法找到一种有效地做到这一点的方法。

基本上我有一个包含问题的表格,并且我有一个表格来跟踪问题的答案以及与该答案相关的用户的用户信息。答案都是对或错,我想跟踪每个问题的总对错答案。

所以第一个查询是选择问题表中的所有记录。第二个查询通过 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 选择器或任何类似的东西。我希望我已经足够清楚了。在遇到这个问题之前,我以为我对查询有很好的理解。

任何帮助将非常感激

4

2 回答 2

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
于 2012-10-09T22:08:52.380 回答
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 
于 2012-10-09T22:20:23.160 回答