问题
I have 2 tables:
townwhich stores 290 townshospitalwhich stores hospitals referenced in 67 different towns
The following query returns 290 rows which is what the LEFT JOIN is supposed to do:
SELECT a.code, count(b.*)
FROM town a
LEFT JOIN hospital b ON a.code = b.town_code
GROUP BY a.code ;
Now, the following query in which I just add a WHERE clause to select a type of hospital returns 56 rows:
SELECT
a.code,
count(b.*)
FROM town a
LEFT JOIN hospital b ON a.code = b.town_code
WHERE b.type = '01'
GROUP BY a.code ;
I don't understand why and I'm wondering how could I get my 290 rows issued with the second query as well?
回答1:
When LEFT JOIN, put the right side table's conditions in the ON clause to get true LEFT JOIN behavior. (When in the WHERE clause, you get regular INNER JOIN result.)
SELECT
a.code,
count(b.*)
FROM town a
LEFT JOIN hospital b ON a.code = b.town_code AND b.type = '01'
GROUP BY a.code
来源:https://stackoverflow.com/questions/35597792/postgresql-left-join-does-not-return-entire-left-table