SQL:如何在表中创建参与约束

时间:2017-10-09 23:52:55

标签: sql create-table erd

让我们说,银行架构如下:

Employee = {*ID*,salary}
Branch = {*BranchNum*, Location}

如果关系同时具有参与约束和关键约束:

Employee ==> workAt -- Branch  //every employee must work at one branch

我可以通过将 BranchNum 设置为 NOT NULL 来强制参与约束:

CREATE TABLE employee (
    ID           INTEGER,
    BranchNum    INTEGER     NOT NULL, 
    PRIMARY KEY (ID)
    FOREIGN KEY (ID) REFERENCES Employee
    FOREIGN KEY (BranchNum) REFERENCES Branch
)

然而,如果只有参与约束但没有关键约束:

Employee === workAt -- Branch  //every employee must work at one or some branches

创建表格时如何设置参与约束?

1 个答案:

答案 0 :(得分:1)

如果你想:

  

//每位员工必须在一个或一些分支机构工作

然后你有一个1-n的关系。您可以使用联结表实现此目的:

CREATE TABLE EmployeeBranches (
    EmployeeBranchId INTEGER AUTO_INCREMENT PRIMARY KEY,
    EmployeeID INTEGER NOT NULL,
    BranchNum INTEGER NOT NULL,
    FOREIGN KEY (EmployeeID) REFERENCES Employee(EmployeeId)
    FOREIGN KEY (BranchNum) REFERENCES Branch(BranchNum)
);