PostgreSQL: LEFT JOIN does not return entire left table

吃可爱长大的小学妹 提交于 2019-12-25 01:11:29

问题


I have 2 tables:

  1. town which stores 290 towns
  2. hospital which 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!