当前位置:   article > 正文

mysql 多 inner join_mySQL多个INNER JOIN

mysql 多个inner join

我们有三个表要查询,以查找每个企业的客户数和每个企业的记录数

这三个表是:

businessDetails

-------------------

businessDetails.ID

businessDetails.name

clientDetails

-------------------

clientDetails.ID

clientDetails.businessDetailsID

records

-------------------

records.ID

records.businessDetailsID

我们一次从两个表中选择一个计数没有任何问题(businessDetails加上clientDetails OR记录).例如

SELECT businessDetails.name AS businessName

, COUNT(clientDetails.businessDetailsID) AS totalClients

FROM `businessDetails`

INNER JOIN clientDetails

ON clientDetails.businessDetailsID = businessDetails.businessDetailsID

GROUP BY

businessDetails.name

ORDER BY

totalClients DESC

此查询为我们提供了预期的良好结果:

--------------------------------

businessName | totalClients

--------------------------------

Initech | 23

Cylon Inc | 148

The Dude Ltd | 71

我们遇到的问题是如何同时对clientDetails和记录进行计数.我们尝试了以下查询,但由于某种原因,它发现它乘以totalClients的数量:

SELECT businessDetails.name AS businessName

, COUNT(clientDetails.businessDetailsID) AS totalClients

, COUNT(records.businessDetailsID) AS totalRecords

FROM `businessDetails`

INNER JOIN clientDetails

ON clientDetails.businessDetailsID = businessDetails.businessDetailsID

INNER JOIN records ON records.businessDetailsID = businessDetails.ID

GROUP BY

businessDetails.name

ORDER BY

totalClients DESC

这会返回如下结果:

--------------------------------------------------------

businessName | totalClients | totalRecords

--------------------------------------------------------

Initech | 93 | 93

Cylon Inc | 398 | 398

The Dude Ltd | 215 | 215

我希望我们只是犯了一些简单的错误.任何帮助将不胜感激.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/989146
推荐阅读
相关标签
  

闽ICP备14008679号