подзапрос против производительности запроса - неточная наука, Google показывает случаи, когда оба являются выгодными, это зависит от структуры данных, необходимо проверить оба, чтобы прийти к вашей правде.
У меня есть подзапрос, который я не могу заменить соединением и могу проверить его производительность.
Предположим, что у вас есть таблица истории цен, вы добавляете записи каждый раз, когда цена или ее характеристики меняются, возьмите этот простой пример: sql fiddle simple sample !
create table price_hist
( hid serial,
product int,
start_day date,
price numeric,
max_discount numeric,
promo_code character(4) );
create table deliveries
( del_id serial,
del_date date,
product int,
quantity int,
u_price numeric);
insert into price_hist (product, start_day,price,max_discount,promo_code)
values
(21,'2018-03-14',56.22, .022, 'Sam2'),
(18,'2018-02-24',11.25, .031, 'pax3'),
(21,'2017-12-28',50.12, .019, 'titi'),
(21,'2017-12-01',51.89, .034, 'any7'),
(18,'2017-12-26',11.52, .039, 'jun3'),
(18,'2017-12-10',10.99, .029, 'sep9');
insert into deliveries(del_date, product, quantity)
values
('2017-12-05',21,4),
('2017-12-20',18,3),
('2017-12-28',21,2),
('2018-05-08',18,1),
('2018-08-20',21,5);
select d.del_id, d.del_date, d.product, d.quantity,
(select price from price_hist h where h.product=d.product order by h.start_day desc limit 1) u_price,
(select max_discount from price_hist h where h.product=d.product order by h.start_day desc limit 1) max_discount,
(select price from price_hist h where h.product=d.product order by h.start_day desc limit 1)*d.quantity total
from deliveries d;
подзапросы находят значения между диапазонами дат, я не смог сделать в postgresql объединение, которое делает то же самое