Tables whose sole purpose is specify a subset of another table

后端 未结 3 834
遇见更好的自我
遇见更好的自我 2020-12-12 05:50

The database I\'m designing has an employees table; there can be multiple types of employees, one of which are medical employees. The database needs to also des

3条回答
  •  旧巷少年郎
    2020-12-12 06:25

    +1 to answer from @Rahul, another alternative is to create an attribute in the employees table. Although I would not use BIT because there are bugs in that data type. Just use BOOLEAN or TINYINT.

    But the way you have it, creating a second table, has the following advantage: the medical_employees_competences is implicitly restricted to reference only medical employees. It cannot reference someone unless they're in that table.

    Another way to provide that constraint is to make the foreign key in the following way:

    CREATE TABLE employees (
        id      INT PRIMARY KEY AUTO_INCREMENT,
        name    VARCHAR(100) NOT NULL
        IsMedical BOOLEAN DEFAULT 0,
        KEY (id, IsMedical)
    );
    
    /* A many-to-many relation between medical employees and
       their competences. */
    CREATE TABLE medical_employees_competences (
        id             INT PRIMARY KEY AUTO_INCREMENT,
        IsMedical      BOOLEAN DEFAULT 1, /* only put 1 in this column */
        medic_id       INT NOT NULL,
        competence_id  INT NOT NULL,
        FOREIGN KEY (medic_id, IsMedical) REFERENCES medical_employees(id, IsMedical),
        FOREIGN KEY (competence_id) REFERENCES medical_competences(id)
    );
    

    Now you can achieve the same constraint, that you can only reference medical employees using the second table.

提交回复
热议问题