SQL查询总和乘以它应该的2倍

时间:2012-05-03 17:15:36

标签: mysql sql sum

当我运行此查询时,投票sum是它应该的2倍(sum = 6而不是3)。有人可以找出解决方案吗?

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

我很确定它与JOIN有关,因为如果我摆脱JOIN items on items_purchased.item_id=items.folder_id则总和= 3。但是,我需要以某种方式加入。

思想?

1 个答案:

答案 0 :(得分:6)

没有架构,我们无法分辨,但这是一个猜测:

检查所有加入条件 - 您可能错过了导致该组结果为“重复”的条件。

例如,如果我有一张表

`Foo` with columns `A` `B` and `C` - A and B are the PK;
`Bar` with columns `A` `B` and `Z` - A and B are the PK;
`Biz` with columns `Z` `GOAL` 

我想计算每A个目标的数量,如果我只是使用A而不是B加入Foo,我可能会得到一个错误的计数

最简单的方法是执行SELECT *并按

删除组