如何更新范围不重叠?

时间:2017-07-14 12:14:09

标签: sql postgresql sql-update

我有一个表foo,其中包含id列(非唯一),start_dateend_date。对于具有特定id的所有行,我希望没有[start_dateend_date)范围重叠。我想通过更改有问题的行的end_date来做到这一点。

我有

update foo old
set end_date = new.start_date
from foo new
where old.start_date < new.start_date and old.end_date > new.start_date
and old.id = new.id and new.id = 8675309;

但是,如果old与其他多条记录重叠,则无法正常工作。我最好的尝试是

update foo old
set end_date = (select coalesce(min(new.start_date), old.end_date)
    from foo new
    where old.start_date < new.start_date and old.end_date > new.start_date
    and new.id = old.id)
where old.id = 8675309;

这样可行,但它会不必要地更新每一行,感觉就像一个黑客。最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

这假设start_dateid

中是唯一的
update foo
set end_date = s.lsd
from (
    select
        id, start_date,
        lead (start_date, 1, end_date) over (
            partition by id order by start_date
        ) as lsd
    from foo
) s
where
    foo.id = s.id and
    foo.start_date = s.start_date and
    foo.end_date > s.lsd