PostgreSQL check constraint for foreign key condition

前端 未结 4 1392
無奈伤痛
無奈伤痛 2020-12-13 10:45

I have a table of users eg:

create table \"user\" (
    id serial primary key,
    name text not null,
    superuser boolean not null default false
);
         


        
4条回答
  •  既然无缘
    2020-12-13 10:59

    Create a separate superuser table that inherits from the user table:

    CREATE TABLE "user" (
        id serial PRIMARY KEY,
        name text NOT NULL,
    );
    
    CREATE TABLE superuser () INHERITS ("user");
    

    The user_has_job table can then reference the superuser table:

    CREATE TABLE user_has_job (
        user_id integer REFERENCES superuser (id),
        job_id integer REFERENCES job(id),
        PRIMARY KEY (user_id, job_id)
    );
    

    Move users around between the tables as needed by inserting and deleting:

    WITH promoted_user AS (
        DELETE FROM "user" WHERE id = 1 RETURNING *
    ) INSERT INTO superuser (id, name) SELECT id, name FROM promoted_user;
    

提交回复
热议问题