I have three tables related to each other in the following way:
- host (has multiple sessions)
- session (has multiple processes)
- processes
The table structure is as follows:
- host table -
id, name - session table -
id, host_id, name - process table -
id, session_id, name
What I am trying to achieve is the count of the number of sessions and the count of the number of processes on each host. To achieve this I tried the following query, but the output is wrong.
select host.id,
count(sessions.id) as "session count",
count(process.id) as "process count"
from host as host
left outer join sessions as sessions on host.id = sessions.host_id
left outer join process as process on sessions.id = process.session_id
group by host.id;
Here's the SQLFiddle to the schema.
As per the data in the fiddle, the output should be:
id | session count | process count
----------------------------------
1 | 2 | 3
2 | 1 | 2
3 | 1 | 2
4 | 2 | 3
But what I get is:
id | session count | process count
----------------------------------
1 | 3 | 3
2 | 2 | 2
3 | 2 | 2
4 | 3 | 3
What can be the correct query to get the desired output?