When I run this query, the votes sum is 2 times what it should be (sum=6 instead of 3). Can someone figure out the fix for this?
SELECT sum(votes.vote) AS sum
, my_votes.vote IS NOT NULL AS did_i_vote
, votes.parent_id, subject
, review_date
, item_id
, review_summary
, review, full_name
, reputation
, profile_picture
, accounts.acct_id
FROM votes
RIGHT JOIN items_purchased
on votes.parent_id=items_purchased.purchase_id
JOIN accounts
ON items_purchased.purchaser_account_id=accounts.acct_id
JOIN items
on items_purchased.item_id=items.folder_id
LEFT JOIN votes AS my_votes
ON my_votes.parent_id=items_purchased.purchase_id
AND my_votes.acct_id='3'
AND my_votes.column_name='purchase_id'
WHERE purchase_id='2'
AND deleted_p!=1 and pub_priv_p!=1
GROUP BY items_purchased.purchase_id
I’m pretty sure it has to do with the JOINs because if I get rid of JOIN items on items_purchased.item_id=items.folder_id then the sum=3. However, I need that JOIN in there somehow.
Thoughts?
Without a schema we can’t tell, but this is a guess:
Check all of your join conditions – you’re likely missing a condition causing that set of results to be ‘duplicated’.
For example, if I have a table
And I wanted to count the number of GOALS per
A, if I joined the Foo to Bar just usingAand notBas well, I would likely get an erroneous count.The easiest way to see this is to do a SELECT * and remove the group by