我有一个包含员工的表,他们都有一个ID;我通过外键在另外两个表(Salesman,Mechanic)中引用此ID。我想要确保的是,员工既可以是机械师,也可以是推销员,但绝不是两者兼而有之。换句话说,我想将这个逻辑与我的外键相关联:
我如何将这样的逻辑集成到表中?我是一名SQL初学者,所以如果这是一个愚蠢的问题我会道歉。
这些是我的表格:
CREATE TABLE [dbo].[Employee]
(
Number INT NOT NULL,
-- ...
PRIMARY KEY(Number)
);
CREATE TABLE [dbo].[Salesman]
(
ID INT NOT NULL,
-- ...
PRIMARY KEY(ID),
FOREIGN KEY(ID) REFERENCES [dbo].[Employee](ID)
);
CREATE TABLE [dbo].[Mechanic]
(
ID INT NOT NULL,
-- ...
PRIMARY KEY(ID),
FOREIGN KEY(ID) REFERENCES [dbo].[Employee](ID)
);
答案 0 :(得分:1)
这是一种关系,在SQL中实现很棘手。这是一种方法:
CREATE TABLE [dbo].[Employee] (
EmployeeId INT PRIMARY KEY,
EmployeeType VARCHAR(32)
-- ...
CHECK (EmployeeType IN ('Mechanic', 'SalesPerson')),
UNIQUE (EmployeeType, EmployeeId)
);
CREATE TABLE [dbo].[SalesPerson]
(
EmployeeId INT PRIMAY KEY,
-- ...
EmployeeType as (CONVERT(VARCHAR(32), 'Salesperson')) PERSISTED,
FOREIGN KEY (EmployeeType, EmployeeId) REFERENCES [dbo].[Employee](EmployeeType, EmployeeId)
);
CREATE TABLE [dbo].[Mechanic] (
EmployeeId INT PRIMARY KEY,
EmployeeType as (CONVERT(VARCHAR(32), 'Mechanic')) PERSISTED,
-- ...
FOREIGN KEY (EmployeeType, EmployeeId) REFERENCES [dbo].[Employee](EmployeeType, EmployeeId)
);
Here是一个说明代码的SQL小提琴。