присоединиться к подзапросу в поисках между диапазонами - PullRequest
0 голосов
/ 14 сентября 2018

подзапрос против производительности запроса - неточная наука, 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 объединение, которое делает то же самое

1 Ответ

0 голосов
/ 15 сентября 2018

Вы можете использовать distinct on для получения значений из price_hist для последних start_day:

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)

Использовать его как производную таблицу, чтобы объединить ее с deliveries:

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)

SqlFiddle.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...