sql - 简单的 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;
无论第二张表中是否有任何匹配记录,都不应该从第一张表中返回数据吗?我究竟做错了什么?
解决方案
where
如果在联接之后应用,则子句中的过滤。所以在这里,您从 中获取所有行products
,并将它们与空adjustments
行匹配(因为表是空的)。然后,您应用where
条件,包括adjustments.website_id = 1
因为adjustment.website_id
always 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;
推荐阅读
- python - 将 gunicorn 与 ubuntu 一起使用:最新的 Docker 映像
- rust - 如何从 rust 宏中的“Foo::Bar”中获取“Bar”?
- sql - 基于使用 Oracle SQL 的图书借阅场景运行不同计数的递增/递减数据
- angular - 我试图从资产目录中获取图像,但是一旦我构建了项目,资产目录就改变了
- javascript - 如何检查它是否包含多个内容?
- javascript - 如何在不单击 chrome 插件中的插件图标的情况下执行 content_script?
- python - 确定函数的参数和关键字参数
- android - 如何在颤动中将底部导航栏图标与当前页面同步
- flutter - 如何从本地视频文件中创建可搜索的字节数据流?
- mysql - 我正在尝试发送不在一行mysql中的消息