title: Postgres LEFT JOIN and COUNT
body: <p>I'm having a bit of trouble debugging a SQL query and would really appreciate some help.</p>
  
  <p>Here is the query:</p>
  
  <pre><code>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);
  </code></pre>
  
  <p>The unexpected behavior comes from the two COUNT statements. I expect upvote_count to be equivalent to </p>
  
  <pre><code>SELECT COUNT(*) FROM upvotes WHERE upvotes.post_id = (individual post id);
  </code></pre>
  
  <p>for each individual post and same for comment count (which I expect to return the total number of comments for each post. However, I am getting strange seemingly random results from these queries for those two fields. Can anybody help me diagnose the problem?</p>