
Originally Posted by
ratamaster
Do you know what's wrong here ?
you're getting cross join effects, because for each main id, you get multiple rows from one of the child tables, and each of those is joined with multiple rows from the other child table
remove the GROUP BY and (temporarily) use SELECT * and you will see the multiplication effect on the number of matched rows
the solution is to put at least one and preferably both of your aggregation operations into a subquery
Code:
SELECT mainTable.id
, sub1.myValue1
, sub2.myValue2
FROM mainTable
LEFT OUTER
JOIN ( SELECT mainTableId
, SUM(childTable1Field1) +
SUM(childTable1Field2) AS myValue1
FROM childTable1
GROUP
BY mainTableId ) AS sub1
ON sub1.mainTableId = mainTable.id
LEFT OUTER
JOIN ( SELECT mainTableId
, COUNT(*) AS myValue2
FROM childTable2
GROUP
BY mainTableId ) AS sub2
ON sub2.mainTableId = mainTable.id
Bookmarks