How to enforce uniques across multiple tables

陌路散爱 提交于 2019-12-05 11:44:18

You're right - #1 is the best option.
Granted, I would question it at first glance (because of shortcutting) but knowing the business rule to ensure an employee is only related to one company - it makes sense.

Additionally, I'd have a foreign key relating the companyid in the employee table to the companyid in the office table. Otherwise, you allow an employee to be related to a company without an office. Unless that is acceptable...

Triggers are a last resort if the relationship can not be demonstrated in the data model, and servicing the logic from the application means the logic is centralized - there's no opportunity for bad data to occur, unless someone drops constraints (which means you have bigger problems).

Each of your company-provided tables should include CompanyID into the `UNIQUE KEY' over the company-provided ids.

Company-provided referential integrity should use company-provided ids:

CREATE TABLE company (
        uid INT NOT NULL PRIMARY KEY,
        name TEXT
        );

CREATE TABLE office (
        uid INT NOT NULL PRIMARY KEY,
        companyID INT NOT NULL,
        externalID INT NOT NULL,
        UNIQIE KEY (companyID, externalID),
        FOREIGN KEY (companyID) REFERENCES company (uid)
        );

CREATE TABLE employee (
        uid INT NOT NULL PRIMARY KEY,
        companyID INT NOT NULL,
        officeID INT NOT NULL,
        externalID INT NOT NULL,
        UNIQIE KEY (companyID, externalID),
        FOREIGN KEY (companyID) REFERENCES company(uid)
        FOREIGN KEY (companyID, officeID) REFERENCES office (companyID, externalID)
        );

etc.

Set auto_increment_increment to the number of table you have. SET auto_increment_increment = 3; (you might want to set this in your my.cnf)

Then manually set the starting auto_increment value of each table to different values first table to 1, second table to 2, third table to 3

Table 1 will have values like 1,4,7,10,13,etc

Table 2 will have values like 2,5,8,11,14,etc

Table 3 will have values like 3,6,9,12,15,etc

Of course this is just ONE option, personally I'd just make it a combo value. Could be as simple as TableID, AutoincrementID, Where the TableID is constant in all rows.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!