MySQL多重聚合

时间:2011-11-15 03:49:12

标签: mysql aggregate-functions

如果没有第三个连接D.cid = C.id,这个查询会给我C的计数。第三个连接会破坏计数并将不需要的元组加入到C的连接数中。那么如何在不影响C计数的情况下获得C和D的计数?是否有一种括号可以用来确保我得到正确的计数?

SELECT A.*, B.*, COUNT(C.aid) AS cCount 
FROM tableA A

LEFT JOIN tableC AS C ON A.id = C.aid
INNER JOIN tableB AS B ON A.id = B.aid
LEFT JOIN tableD AS D ON D.cid = C.id

GROUP BY  A.id

1 个答案:

答案 0 :(得分:1)

我会将其他表中的计数预先汇总到自己并加入......类似......

SELECT 
      A.*, 
      B.*, 
      COALESCE( PreAggC.CCount, 0 ) as CCount,
      COALESCE( PreAggC.WithDCount, 0 ) as WithDCount
   FROM 
      tableA A

         JOIN tableB B
            on A.ID = B.aID

         LEFT JOIN ( select aID, 
                            count( distinct id ) CCount,
                            count(*) as WithDCount
                        from tableC
                           left join tableD D
                              on c.ID = D.cID
                        group by aID ) PreAggC
            on A.id = PreAggC.aID

现在,您真的想要有多少条目实际上有“D”记录吗?所以我包括两个计数...不同的“C”条目,以及与“D”相关的整体计数