title: Postgres - Multiple joins is causing my query to return incorrect data
body: <p>I have three tables in my database. Their schema is basically:</p>
  
  <pre><code>books:
  id | book_title
  
  books_tags:
  id | book_id | tag_id
  
  books_votes:
  id | book_id | vote
  </code></pre>
  
  <p>The idea is to be able to search for books and filter by given tags (716 and 101, in this case). The <code>total_votes</code> is used in the ORDER BY caluse.</p>
  
  <pre><code>SELECT
      books.id AS books_id, sum(book_votes.vote) AS total_votes 
  FROM
      books
  JOIN
      -- works fine without this join
      book_votes ON books.id = book_votes.book_id
  JOIN
      books_tags ON books.id = books_tags.book_id
  WHERE
      books_tags.tag_id IN (716, 101)
  GROUP BY
      books.id 
  HAVING
      count(books.id) = 2
  </code></pre>
  
  <p>The tag filtering, by itself, works great. I can add as many tag ids to the IN clause as I wish and it will continue to filter the results to only show books with those tags. Perfect.</p>
  
  <p>The problem occurs when I add in the second JOIN to the <code>books_votes</code> table. This join doesn't produce any errors it just causes the query to return the wrong data - Like it's ignoring the tag ids.</p>
  
  <p>What's wrong with having the second join?</p>
  
  <p>EDIT:</p>
  
  <p>Here's the dumps from the tables:</p>
  
  <pre><code>books:
   id |   book_title  
  ----+-----------------
    1 | first
    2 | second
    3 | third book
    4 | fourth book
    5 | fifth
    6 | sixth book
  
  books_tags:
   id | book_id | tag_id 
  ----+---------+--------
    1 |       1 |    293
    2 |       1 |     32
    3 |       1 |    370
    4 |       2 |    101
    5 |       2 |    357
    6 |       3 |    554
    7 |       3 |    808
    8 |       3 |    716
    9 |       3 |    101
   10 |       4 |    787
   11 |       4 |    808
   12 |       4 |    322
   13 |       5 |    787
   17 |       6 |    716
   18 |       6 |    554
   19 |       6 |    101
  
  books_votes:
   id | book_id | vote 
  ----+---------+------
    2 |       2 |    1
    3 |       3 |    1
    4 |       4 |    1
    7 |       4 |    1
    8 |       2 |    1
   11 |       5 |    1
   12 |       5 |    1
   13 |       1 |    1
  </code></pre>
  
  <p>Here's the data returned, from the query I posted, when I leave out the second join (to books_votes):</p>
  
  <pre><code> book_id 
  ---------
     6
     3
  </code></pre>
  
  <p>As you can see, the correct books are returned. Books 6 and 3 have been tagged with the ids 716 and 101.</p>
  
  <p>Here's what's returned when I run the query with the books_votes table joined:</p>
  
  <pre><code> book_id | total_votes 
  ---------+-------------
      3    |    2
      2    |    3
  </code></pre>