Here are 3 tables :
cities(id PK, name, zipcode)
jobs(id PK, title)
persons(id PK, first_name, last_name, job_id FK jobs, city_id FK cities)
Each person has a job and lives in a city, both cities and jobs can have at least 0 persons (0..n).
I would like to count persons for each job and city without removing cities and jobs which do not have persons :
> +----------+----------+---------------+
| city_id | job_id | count(p.id) |
+------------+----------+---------------+
| 140 | 1 | 0 |
| 249 | 37 | 1 |
| 249 | 40 | 1 |
| 249 | 269 | 1 |
| 250 | 4823 | 3 |
| 251 | 1 | 4 |
| 251 | 205 | 1 |
| 433 | 1 | 0 |
| 433 | 40 | 1 |
| 433 | 23 | 1 |
| 433 | 1346 | 1 |
| 434 | 5 | 5 |
| 434 | 70 | 1 |
| 434 | 5332 | 1 |
I guess the query should look like so :
SELECT job_id, city_id, COUNT(p.id)
FROM persons p
???? JOIN jobs j ON p.job_id=j.id
???? JOIN cities c ON p.city_id=c.id
GROUP BY j.id, c.id
I know it cannot be done using an INNER JOIN as all rows containing no joined references will be ignored.
I tried RIGHT JOIN but depending upon JOIN's order results are not the same.