如何排除总票数小于1的帖子?

时间:2016-09-13 00:55:35

标签: mysql sql

这是我的问题:

SELECT count(1)
 FROM qanda question
 JOIN qanda answer ON question.Id = answer.related
WHERE answer.related IS NOT NULL
  AND answer.author_id = ?
  AND question.amount IS NULL
  AND answer.date_time >= UNIX_TIMESTAMP(now() - INTERVAL 1 YEAR) AND UNIX_TIMESTAMP(now() - INTERVAL 1 hour)
  AND answer.id NOT IN (
      SELECT post_id
      FROM votes
      WHERE table_code = 15
      GROUP BY post_id
      HAVING SUM(value) < 0 )

我的查询返回用户的答案数为零或总票数(总票数:0,1,2,......)。现在我需要排除0总票数的答案。

因此我取代:

... HAVING SUM(value) < 0

... HAVING SUM(value) < 1

但它没有按预期工作。我的意思是它仍然计算总票数为零的答案。怎么了?我该如何解决?

2 个答案:

答案 0 :(得分:1)

如果我理解正确,请使用in代替not in并反转您的having条件:

...
answer.id IN (
      SELECT post_id
      FROM votes
      WHERE table_code = 15 
      GROUP BY post_id
      HAVING SUM(value) > 0)

答案 1 :(得分:1)

问题是您的内部查询没有选择投票的帖子,因此不排除 。有几种方法可以解决这个问题,但最简单的方法是排除的逻辑从反向转换为包含,即&#34; show已投票总数的帖子&gt; 1&#34;:

SELECT count(1)
 FROM qanda question
 JOIN qanda answer ON question.Id = answer.related
WHERE answer.related IS NOT NULL
  AND answer.author_id = ?
  AND question.amount IS NULL
  AND answer.date_time BETWEEN UNIX_TIMESTAMP(now() - INTERVAL 1 YEAR) AND UNIX_TIMESTAMP(now() - INTERVAL 1 hour)
  AND answer.id IN ( -- remove "NOT"
      SELECT post_id
      FROM votes
      WHERE table_code = 15
      GROUP BY post_id
      HAVING SUM(value) > 0 ) -- change to > 0

作为加入:

SELECT count(*) FROM (
  SELECT answer.id
  FROM qanda question
  JOIN qanda answer ON question.Id = answer.related
  JOIN votes ON votes.post_id = answer.id 
      AND votes.table_code = 15
   WHERE answer.related IS NOT NULL
   AND answer.author_id = ?
   AND question.free IS NULL
   AND answer.date_time BETWEEN UNIX_TIMESTAMP(now() - INTERVAL 1 YEAR)
     AND UNIX_TIMESTAMP(now() - INTERVAL 1 hour)
   AND answer.timestamp > subdate(now(), 365)
   GROUP BY answer.id
  HAVING SUM(votes.value) > 1) x