sql - 如果联接表不返回结果,则不返回任何行

标签 sql postgresql

我现在正在使用多个内部联接,但其中一个表可能根本不包含任何结果。

下面是我目前正在使用的查询

SELECT
   property.id,
   full_address,
   street_address,
   street.street,
   city.city as city,
   state.state_code as state_code,
   zipcode.zipcode as zipcode, 
   property_history.date_event AS event_date,
   property_history.event AS event
FROM
    property 
    INNER JOIN street  ON street.id = property.street_id 
    INNER JOIN city    ON city.id = property.city_id
    INNER JOIN state   ON state.id = property.state_id
    INNER JOIN zipcode ON zipcode.id = property.zipcode_id
    INNER JOIN property_history ON property_history.property_id = property.id
WHERE
    full_address = ?

现在,如果 property_history 没有返回任何行,那么我将一无所获。我假设我需要使用其他类型的连接?

我仍然想获取 property.idfull_addressstreet_address 等,即使 property_history是空的。

最佳答案

你应该使用LEFT OUTER JOIN:

LEFT JOIN property_history ON property_history.property_id = property.id

关于sql - 如果联接表不返回结果,则不返回任何行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57739624/

相关文章:

ruby-on-rails - Group by 和 order by 在 Rails 中有很多直通模型

node.js - 在 Sequelize 中使用迁移添加具有外键约束的表列

python - Django 1.8 错误 : No database fixture specified

sql - 您试图在 ms access 中执行不包含指定表达式 'out_time' 作为聚合函数的查询

sql - Microsoft Access 2010 中 SQL 查询的最大长度?

sql - 获取 Postgres 数据库中每个表的行数

postgresql - 将 200GB 的 Postgres 数据从 9.0 迁移到 9.6

mysql - 使用删除 SQL 查询的限制

mysql - 需要为表中存在的每一行获取 true/false

sql - 将字符串的所有实例提取到连接结果中