简体   繁体   English

创建两个具有相同主键的子类型(或子)表,该主键也是父表的外键 sql

[英]Create Two Subtype (or child) tables with same primary key which is also a foreign key to the parent table sql

I have the following tables:我有下表:

CREATE TABLE employee(
    id INT(11) UNSIGNED PRIMARY KEY,
    namee VARCHAR(60) NOT NULL)
ENGINE = InnoDB;
CREATE TABLE consierge(
    id INT(11) UNSIGNED PRIMARY KEY,
    namee VARCHAR(60) NOT NULL, 
    zonee VARCHAR(20), 
    functionn VARCHAR(20),
    FOREIGN KEY (id) REFERENCES employee(id))
ENGINE = InnoDB;
CREATE TABLE guard(
    id INT(11) UNSIGNED PRIMARY KEY,
    namee VARCHAR(60) NOT NULL, 
    rol VARCHAR(20) NOT NULL,
    wtime ENUM ('Day','Night'),
    FOREIGN KEY (id) REFERENCES employee(id)) 
ENGINE = InnoDB;

When I try to create an consierge or guard, it firts verify the existence of that id in employee, which is fine.当我尝试创建礼宾或守卫时,它会首先验证员工中是否存在该 ID,这很好。 The problem is that, ie, when an id is already in guard (hence in employee) and I create an consierge with that same id, the consierge gets created, so, an employee can be guard and consierge;问题是,即,当一个 id 已经在守卫中(因此在员工中)并且我创建了一个具有相同 id 的 consierge 时,consierge 被创建,因此,员工可以是守卫和 consierge; and I want that an employee can be guard OR consierge EXCLUSIVElY.我希望员工可以专心看守或看门。

You can do this -- without triggers -- using some additional logic with generated columns:您可以执行此操作——无需触发器——对生成的列使用一些额外的逻辑:

CREATE TABLE employee(
    id INT(11) UNSIGNED PRIMARY KEY,
    namee VARCHAR(60) NOT NULL,
    type varchar(255),
    c_id int generated always as (case when type = 'c' then id end) stored,
    g_id int generated always as (case when type = 'g' then id end) stored,
    check (type in ('c', 'g'))
);

CREATE TABLE consierge (
    id INT(11) UNSIGNED PRIMARY KEY,
    namee VARCHAR(60) NOT NULL, 
    zonee VARCHAR(20), 
    functionn VARCHAR(20),
    type varchar(255) generated always as ('c') stored,
    unique (type, id),
    FOREIGN KEY (id) REFERENCES employee(id)
);

CREATE TABLE guard(
    id INT(11) UNSIGNED PRIMARY KEY,
    namee VARCHAR(60) NOT NULL, 
    rol VARCHAR(20) NOT NULL,
    wtime ENUM ('Day','Night'),
    type varchar(255) generated always as ('g') stored,
    unique (stored, id),
    FOREIGN KEY (id) REFERENCES employee(id)
);

ALTER TABLE employee ADD CONSTRAINT fk_employee_c_id
    FOREIGN KEY (c_id) REFERENCES concierge(id);

ALTER TABLE employee ADD CONSTRAINT fk_employee_g_id
    FOREIGN KEY (g_id) REFERENCES guard(id);

This adds computed columns to allow the desired foreign key relationships.这将添加计算列以允许所需的外键关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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