We have three tables that we would like to query to find out the count of clients per business and the number of records per business
The three tables are:
businessDetails
-------------------
businessDetails.ID
businessDetails.name
clientDetails
-------------------
clientDetails.ID
clientDetails.businessDetailsID
records
-------------------
records.ID
records.businessDetailsID
We don't have any problem with being able to select a count from two of the tables at one time (businessDetails plus either clientDetails OR records). For example
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
This query gives us a nice result as expected:
--------------------------------
businessName | totalClients
--------------------------------
Initech | 23
Cylon Inc | 148
The Dude Ltd | 71
The problem we are running into is how to do a count on both clientDetails AND records at once. We tried the following query, but have found that it multiplies the number of totalClients for some reason:
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
This returns a result something like:
--------------------------------------------------------
businessName | totalClients | totalRecords
--------------------------------------------------------
Initech | 93 | 93
Cylon Inc | 398 | 398
The Dude Ltd | 215 | 215
I expect we're just making some simple error. Any help would be greatly appreciated.