赞
踩
我们有三个表要查询,以查找每个企业的客户数和每个企业的记录数
这三个表是:
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
我希望我们只是犯了一些简单的错误.任何帮助将不胜感激.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。