Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL-多连接关系和计数行_Mysql_Sql_Count_Jointable - Fatal编程技术网

MySQL-多连接关系和计数行

MySQL-多连接关系和计数行,mysql,sql,count,jointable,Mysql,Sql,Count,Jointable,我想用性能良好的方法构建SQL查询。我需要选择所有类别并计算与此类别关联的波段 结构: 乐队: id | band_name |cat_id ----------|----------------|------------ 1 | Business 1 | 1 2 | Business 12 | 2 3 | Business 123 | 2 类别: id | name

我想用性能良好的方法构建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

结果非常奇怪——每行的带数之和为5到3。不要责怪我的结构-我不得不修改它,因为需求规范发生了变化。

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

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;

您甚至不需要
波段
表来计算它们。这些信息在connections表中。

请通过添加适当的标记(Oracle、SQL Server、MySQL等)来指定目标RDBMS。可能有一些答案利用了并非普遍支持的语言或产品功能。此外,通过使用特定的RDBMS标记,您的问题可能会得到更适合回答它的人的注意。