mysql查询从相关表中计数两次

时间:2016-05-26 20:32:11

标签: mysql

我在按照我想要的方式查询问题时遇到了问题。我有2张桌子: 段落和问题表

问题表有一个Passage的外键。问题表有一个名为status的列,它处于活动状态,非活动状态或查看状态。我能够得到活跃问题的数量,但现在我想在审查中得到问题的数量,但我似乎无法弄清楚它。以下是我到目前为止提出的问题,但问题审查专栏只给了我与数字相同的数字。

SELECT 
p."id",  
COUNT(q."PassageId") as numQuestions, 
COUNT(q2."PassageId") AS questionsInReview, 
ROUND(AVG(q."level")) as "questionLevel" 
FROM 
"Passages" as p 
LEFT OUTER JOIN "Questions" as q ON p.id=q."PassageId" AND q."status" = 'active'
LEFT OUTER JOIN "Questions" as q2 on p.id=q2."PassageId" where q2."status" = 'review'
GROUP BY p.id 
ORDER BY p.id ASC

我应该如何设置查询以便能够查看审核中的问题数量?

编辑:

在玩完这里建议的是我开始工作之后

解决方案:

SELECT 
   p.id, 
   SUM(CASE WHEN q."status" = 'active' THEN 1 ELSE 0 END) AS numQuestions, 
   SUM(CASE WHEN q."status" = 'review' THEN 1 ELSE 0 END) AS questionsInReview, 
   ROUND(AVG(CASE WHEN q."status" = 'active' THEN q."level" ELSE Null END)) as questionLevel
FROM "Passages" AS p 
LEFT JOIN "Questions" as q ON p.id = q."PassageId"
GROUP BY p.id 
ORDER BY p.id ASC

2 个答案:

答案 0 :(得分:1)

如何(未经测试):

SELECT p.id,  
       COUNT(q.id) AS numQuestions, 
       SUM(q.status = "review") AS questionsInReview, 
       ROUND(AVG(if(q.status = "active", q.level, null)) as questionLevel
FROM Passages AS p 
LEFT JOIN Questions as q ON p.id = q.PassageId AND q.status = 'active'
GROUP BY p.id 
ORDER BY p.id ASC

答案 1 :(得分:1)

你的回答的问题是你只是计算行数 - 因为你加入了,行数是相同的。

尝试这种方法:

SELECT id, sum(active) as sum_active, sum(review) as sum_review from (
  SELECT p.id, 
    CASE q.status WHEN 'active' 1 ELSE 0 AS active,
    CASE q.status WHEN 'review' 1 ELSE 0 AS review
  FROM Passages as p inner join Questions as q ON p.id = q.passageId
) group by id

这个想法 - 内部查询只会为您提供活动和审核的二进制列。通过这种方式,您可以简单地总结它们以获得结果