Mysql counts records from two tables in one query?
I have three MySQL tables:
patient:
paID, paCode, paAccountID (foreign key)
test
tsID, tsName, tsPatientID (foreign key), tsAccountID (foreign key)
account
acID etc.
Now I want to count the quantity paID
and number tsID
that are associated with a specific one acID=1
. There are 6 tsID
and 4 paID
related acID=1
.
SELECT Count(paID) AS paCount FROM patient WHERE paAccountID=1
SELECT Count(tsID) AS tsCount FROM test WHERE tsAccountID=1
Tried to get both in one request ...
SELECT Count(tsID) AS tsCount, Count(paID) AS paCount
FROM test LEFT JOIN patient ON tsPatientID = paID
WHERE tsAccountID=1
Doesn't work like this, both Counts are returned 6. How to do this correctly?
source to share
I think this should work if your tsId and paId are unique keys:
SELECT Count(DISTINCT t.tsID) AS tsCount,
Count(DISTINCT p.paID) AS paCount
FROM account a
LEFT JOIN test t ON a.acId = t.tsAccountId
LEFT JOIN patient p ON a.acId = p.paAccountId
WHERE a.acId = 1
And here is the SQL Fiddle .
Please note, the problem with not joining the accounts table (and using it as the master table) is that if there is no data in the test table or patient table for a specific account id, the query will return 0 results for each - which could be wrong.
source to share