I hope someone can help me with my MySQL problem. I have a bug where if there is one left outer join on contribution table, result of amount is $100 (which is correct). If I include a second left outer join of another table (ikes). And I have 2 ikes, it doubles amount ($200), if I have 3 ikes, it triples ($300). For the life of me, I cannot figure this out. What do the ikes have any to do with the contribution amount? I’ve separated the queries and they work by themselves. But together they cause the problem.
Can anyone see the problem? I’ve included the query and the tables below.
SELECT COUNT(i.type) AS xlike,
SUM(c.amount) AS amount,
w.*
FROM wish w
LEFT OUTER JOIN contributions c ON w.ID=c.receiveid
LEFT OUTER JOIN ikes i ON w.ID=i.wishid
WHERE w.ID = 236
Tables:
CREATE TABLE IF NOT EXISTS `contributions` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`amount` decimal(19,2) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
CREATE TABLE IF NOT EXISTS `ikes` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`type` enum('likes','dislikes') NOT NULL,
`wishid` int(11) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
While most will tell you to use JOINs, you have to be aware that joins will duplicate parent records if more than one child record is associated to it. This is what can inflate values from aggregate functions.
I re-wrote your query as: