问题
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