Postgresql 在范围之间的搜索中连接vs子查询
子查询vs查询的性能是一门不准确的科学,谷歌展示了两者都有优势的情况,这取决于数据结构,有必要对两者进行测试以得出您的结论 我有一个子查询,我不能用join替换它,并且可以测试它的性能 假设您有一个价格历史记录表,每次价格或其特征发生变化时都会添加记录,举个简单的例子:Postgresql 在范围之间的搜索中连接vs子查询,postgresql,performance,join,subquery,Postgresql,Performance,Join,Subquery,子查询vs查询的性能是一门不准确的科学,谷歌展示了两者都有优势的情况,这取决于数据结构,有必要对两者进行测试以得出您的结论 我有一个子查询,我不能用join替换它,并且可以测试它的性能 假设您有一个价格历史记录表,每次价格或其特征发生变化时都会添加记录,举个简单的例子: 子查询查找日期范围之间的值,我无法在postgresql中执行相同的联接您可以使用distinct on从price\u hist获取最新开始日期的值: select distinct on(product) prod
子查询查找日期范围之间的值,我无法在postgresql中执行相同的联接您可以使用
distinct on
从price\u hist
获取最新开始日期的值
:
select distinct on(product)
product, price, max_discount
from price_hist h
order by product, start_day desc
product | price | max_discount
---------+-------+--------------
18 | 11.25 | 0.031
21 | 56.22 | 0.022
(2 rows)
将其用作派生表,以将其与交付连接起来
:
select
d.del_id, d.del_date, d.product, d.quantity,
h.price as u_price, h.max_discount, h.price * d.quantity as total
from deliveries d
join (
select distinct on(product)
product, price, max_discount
from price_hist
order by product, start_day desc
) h using(product)
谢谢@kiin,请原谅,我原来的SQLFIDLE不完整(错误),它应该包含h.product=d.product和h.start\u day。在这种情况下,连接效率较低,尽管似乎每个记录都重复子查询
select
d.del_id, d.del_date, d.product, d.quantity,
h.price as u_price, h.max_discount, h.price * d.quantity as total
from deliveries d
join (
select distinct on(product)
product, price, max_discount
from price_hist
order by product, start_day desc
) h using(product)