Prevent INSERT if time overlap in PgSQL without trigger [duplicate]

左心房为你撑大大i 提交于 2020-01-06 19:33:11

问题


i would like to prevent an insert into my PgSQL table if the values for a time period (lets call them newStart and newEnd), if this would overlap with any other timeperiod in my rows. So, the table has a bunch of row where each has a start and end date (oldStart and oldEnd).

Is it possible to do this inside the query, without an trigger, an without getting all the data from the db first end check it inside php (because i think this is not ne best/fastest way to do). Please correct me i think wrong. I found the PgSQL overlap function, but building a query was not possible for me! How can i get more in touch with advanced database things? Just by doing?


回答1:


Use an exclusion constraint.

More elegant with actual range types instead of start/end:

  • Preventing adjacent/overlapping entries with EXCLUDE in PostgreSQL

But you can also use an expression in the constraint. Basically:

CREATE TABLE tbl (
   tbl_id    serial PRIMARY KEY
 , starts_at timestamp
 , ends_at   timestamp
 , EXCLUDE USING gist (tsrange(starts_at, ends_at) WITH &&) -- no overlapping
);

More details:

  • Postgres constraint for unique datetime range

How can I get more in touch with advanced database things?

Study answers here, read the excellent manual, experiment with newly found techniques.



来源:https://stackoverflow.com/questions/28784729/prevent-insert-if-time-overlap-in-pgsql-without-trigger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!