MySQL - 多个连接关系和计数行

时间:2013-08-22 20:35:40

标签: mysql sql count jointable

我想用性能良好的方法构建SQL查询。我需要选择所有类别并计算与此类别相关的频段。

结构:

带:

 id       | band_name      |cat_id
----------|----------------|------------
 1        | Business 1     | 1  
 2        | Business 12    | 2
 3        | Business 123   | 2

类:

id        | name           
----------|----------------
 1        | Business 1     
 2        | Business 12    
 3        | Business 123   

连接:

id        | band_id        |cat_id
----------|----------------|------------
 1        | 1              | 1  
 2        | 2              | 1
 3        | 2              | 1

查询:

SELECT c.name AS category_name, (SELECT COUNT(icc.band_id) FROM cms_bands_categories_connections AS icc RIGHT JOIN cms_bands AS ib ON icc.band_id = ib.id) AS bands_sum FROM 
                    cms_bands_categories AS c 
                 JOIN cms_bands_categories_connections AS cc ON 
                    c.id = cc.category_id 
                GROUP BY
                    c.id

结果非常奇怪 - bands_sum每行都变为3。不要责怪我的结构 - 我不得不因为需求规范的变化而改变它。

1 个答案:

答案 0 :(得分:1)

为什么使用子查询而不仅仅是聚合?

SELECT c.name AS category_name, COUNT(cc.band_id) AS bands_sum
FROM cms_bands_categories c JOIN
     cms_bands_categories_connections cc
     ON c.id = cc.category_id 
GROUP BY c.id;

您甚至不需要bands表来计算它们。该信息位于连接表中。