首页 > 解决方案 > 简单的 Postgres 查询不返回任何结果

问题描述

我有两张桌子:

products(id: integer, price: float, website_id: integer) 

adjustments(id: integer, product_id: integer, website_id: integer, factor:float)

我在两个表中都有关于 id 的索引,以及在调整表上的 website_id 和 product_id 上的索引。

此查询返回数据,但大约需要 5 秒,大约 1k 产品和几百个调整:

select 
    products.id, 
    case
    when adjustments.website_id = 1
    then
        products.price+coalesce(adjstments.factor,0)
    else
        products.price
    end as price
from
    products
left join
    adjustments on products.id = adjustments.product_id
where
    products.website_id = 1;

但是,当调整表中没有任何内容时,此其他查询不会返回任何结果:

select 
    products.id, 
    products.price+coalesce(adjstments.factor,0) as price
from
    products
left join
    adjustments on products.id = adjustments.product_id
where
    products.website_id = 1 and adjustments.website_id = 1;

无论第二张表中是否有任何匹配记录,都不应该从第一张表中返回数据吗?我究竟做错了什么?

标签: sqlpostgresqlselectleft-join

解决方案


where如果在联接之后应用,则子句中的过滤。所以在这里,您从 中获取所有行products,并将它们与空adjustments行匹配(因为表是空的)。然后,您应用where条件,包括adjustments.website_id = 1因为adjustment.website_idalways null,不返回任何行。

您可以将此条件移至join以获得您期望的行为:

select 
    products.id, 
    products.price+coalesce(adjstments.factor,0) as price
from
    products
left join
    adjustments on products.id = adjustments.product_id and adjustments.website_id = 1
where
    products.website_id = 1;

推荐阅读