“polymorphism” for FOREIGN KEY constraints

前端 未结 1 2026
天涯浪人
天涯浪人 2021-02-19 06:36

There is this field in a table:

room_id INT NOT NULL CONSTRAINT room_id_ref_room REFERENCES room

I have three 2 tables for two kinds of rooms:

1条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-19 07:05

    Here is the pattern I've been using.

    CREATE TABLE room (
        room_id serial primary key,
        room_type VARCHAR not null,
    
        CHECK CONSTRAINT room_type in ("standard_room","family_room"),
        UNIQUE (room_id, room_type)
    );
    
    CREATE_TABLE standard_room (
        room_id integer primary key,
        room_type VARCHAR not null default "standard_room",
    
        FOREIGN KEY (room_id, room_type) REFERENCES room (room_id, room_type),
        CHECK CONSTRAINT room_type  = "standard_room"
    );
    CREATE_TABLE family_room (
        room_id integer primary key,
        room_type VARCHAR not null default "family_room",
    
        FOREIGN KEY (room_id, room_type) REFERENCES room (room_id, room_type),
        CHECK CONSTRAINT room_type  = "family_room"
    );
    

    That is, the 'subclasses' point at the super-class, by way of a type descriminator column (such that the pointed to base class is of the correct type, and that primary key of the super class is the same as the child classes.

    0 讨论(0)
提交回复
热议问题