简体   繁体   中英

Postgres unique constraint across multiple values of a column

I've got a tricky uniqueness requirement in one of my tables.

Say we're got a table of dogs. Dogs live in houses.

CREATE TABLE dogs (
  dog_id integer,
  house_id integer,
  dogname varchar
}

A dog's name must be unique within a house. There is also a "main" house, and no dog may have a name that is the same as a dog in the main house.

Example, where house_id 0 is the "main" house:

dog_id house_id dogname
1      0        Fido
2      0        Rover
3      1        Shep
4      1        Shep  // FAIL, not unique in house 1
5      2        Shep  // ok, allowed
6      2        Fido  // FAIL, conflict with main house

How do I create a uniqueness constraint that models this?

I'm thinking there is a way to do it with an exclusion constraint, but I haven't figured out how.

I would prefer to do this with a constraint instead of a trigger because I also want to do upserts on this table, and you can only use ON CONFLICT with constraints.

For future visitors: the only way I could solve this was to query for a conflicting record first, and then do the insert only if there was none. This works if you wrap both commands in a transaction. I had to do this in the application, not at the database level. Not an ideal solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM