Postgres LEFT JOIN和COUNT

时间:2017-01-09 14:14:11

标签: sql postgresql join count left-join

我在调试SQL查询时遇到了一些麻烦,非常感谢一些帮助。

以下是查询:

SELECT p.id, p.type, p.submission_id, 
  p.title, p.description, p.date, extract('epoch' FROM p.time) AS time, 
  podcasts.image_url, podcasts.title AS podcast_title, 
  COUNT(u1) as upvote_count, u2.id as upvote_id, 
  episodes.mp3_url, episodes.duration, 
  COUNT(c) as comment_count 
FROM posts AS p LEFT JOIN upvotes AS u1 ON p.id=u1.post_id AND u1.comment_id=-1 
LEFT JOIN upvotes AS u2 ON p.id=u2.post_id AND u2.user_id=$1 AND u2.comment_id=-1 
LEFT JOIN episodes ON p.submission_id = episodes.id 
LEFT JOIN podcasts ON episodes.podcast_id=podcasts.id 
LEFT JOIN comments AS c ON c.post_id=p.id 
WHERE p.type='podcast' AND p.time IS NOT NULL 
GROUP BY(p.id, u2.id, podcasts.image_url, episodes.mp3_url, episodes.duration, podcasts.title);

意外行为来自两个COUNT语句。我希望upvote_count等同于

SELECT COUNT(*) FROM upvotes WHERE upvotes.post_id = (individual post id);
每个帖子的

和评论计数的相同(我希望返回每个帖子的评论总数。但是,对于这两个字段,我从这些查询得到奇怪的看似随机的结果。任何人都可以帮我诊断问题

1 个答案:

答案 0 :(得分:2)

count()(以及所有其他聚合函数)忽略空值。

但是,COUNT(c)引用表别名c中的完整行("记录")但是这总是不是null ,即使该记录的所有列都为空。

您需要更改count()次调用并将该表中的传递给它,例如count(u1.post_id)count(c.post_id)