create table T(
  id_t                  integer  not null PRIMARY KEY,
  nazwa                 varchar  (80)
);

create table K(
id_k                  integer  not null,
id_t                  integer  not null references T,
data_k                date     not null,
primary key(id_t,data_k)
);

create table TP(
 id_t                  integer  not null references T,
 nr                    smallint not null,
 date_diff             smallint not null default 0
);
create index ind_tp_t on TP(id_t);

insert into T values (1,'aa');
insert into T values (2,'bb');
insert into K values (1,1,'2001-09-12');
insert into K values (2,1,'2001-09-13');
insert into K values (3,1,'2001-09-14');
insert into K values (4,1,'2001-09-15');
insert into K values (5,2,'2001-09-12');
insert into K values (6,2,'2001-09-13');
insert into K values (7,2,'2001-09-14');
insert into K values (8,2,'2001-09-15');
insert into K values (9,2,'2001-09-16');

insert into TP values (1,1,0);
insert into TP values (2,3,0);

create view bla as select
  T1.id_t,
  K1.data_k+TP.date_diff as data1,
  TP.nr
  from
   (select * from T limit 1) T1
   inner join TP on (TP.id_t=T1.id_t)
   inner join K K1 on (TP.id_t=K1.id_t and K1.data_k='2001-09-23')
   inner join K K2 on (TP.id_t=K2.id_t and K2.data_k=K1.data_k+TP.date_diff);

create view bla2 as select
  T1.id_t,
  K1.data_k+TP.date_diff as data1,
  TP.nr
  from
   (select * from T limit 1) T1
   inner join TP on (TP.id_t=T1.id_t)
   inner join K K1 on (TP.id_t=K1.id_t) -- and K1.data_k='2001-09-23')
   inner join K K2 on (TP.id_t=K2.id_t and K2.data_k=K1.data_k+TP.date_diff);
select * from pg_indexes where tablename in ('t','k','tp');
explain select * from bla where id_t=1;
explain select * from bla2 where id_t=1 and data1='2001-09-24';

drop view bla2;
drop view bla;
drop table TP;
drop table K;
drop table T;

