在 PostgreSQL 中,有issue
表和子issue_step
表 - 一个问题包含一个或多个步骤。
视图issue_v
从问题和第一步和最后一步中拉出东西:author
并且from_ts
从第一步中拉出,而status
和thru_ts
从最后一步中拉出。
桌子
create table if not exists seeplai.issue(
isu_id serial primary key,
subject varchar(240)
);
create table if not exists seeplai.issue_step(
stp_id serial primary key,
isu_id int not null references seeplai.issue on delete cascade,
status varchar(12) default 'open',
stp_ts timestamp(0) default current_timestamp,
author varchar(40),
notes text
);
风景
create view seeplai.issue_v as
select isu.*,
first.stp_ts as from_ts,
first.author as author,
first.notes as notes,
last.stp_ts as thru_ts,
last.status as status
from seeplai.issue isu
join seeplai.issue_step first on( first.isu_id = isu.isu_id and not exists(
select 1 from seeplai.issue_step where isu_id=isu.isu_id and stp_id>first.stp_id ) )
join seeplai.issue_step last on( last.isu_id = isu.isu_id and not exists(
select 1 from seeplai.issue_step where isu_id=isu.isu_id and stp_id<last.stp_id ) );
note1:issue_step.stp_id
保证按时间顺序排列,所以使用它而不是stp_ts
因为它已经被索引
这可行,但丑陋如罪,并且不能成为世界上最有效的查询。