我正在设计的数据库有一个员工表;可以有多种类型的员工,其中一种是医疗员工.数据库还需要描述医疗员工与他们拥有的能力之间的多对多关系.
是否可以创建一个只有id列的表medical_employees,其唯一目的是指定哪些员工是医务人员? id列具有引用employees表的外键约束.下面的代码应该让我的问题更加清晰:
/* Defines a generic employee */
CREATE TABLE employees (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL
);
/* Specifies which employees are medics */
CREATE TABLE medical_employees (
id INT NOT NULL,
FOREIGN KEY (id) references employees(id);
);
/* Specifies what competences a medic can have */
CREATE TABLE medical_competences (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL
);
/* A many-to-many relation between medical employees and
their competences. */
CREATE TABLE medical_employees_competences (
id INT PRIMARY KEY AUTO_INCREMENT,
medic_id INT NOT NULL,
competence_id INT NOT NULL,
FOREIGN KEY (medic_id) REFERENCES medical_employees(id),
FOREIGN KEY (competence_id) REFERENCES medical_competences(id)
);
解决方法:
为什么单独的表格.为什么不创建一个BIT /布尔字段说IsMedical并为员工表中的医疗员工设置为TRUE
/* Defines a generic employee */
CREATE TABLE employees (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
IsMedical BIT(1)
);
这样,如果你想从Employee表中获得所有医疗员工;你只需要在WHERE条件中做一个单独的过滤器,说WHERE IsMedical = true.然而,如果你去一个单独的表,那么你将与medical_employees和employees表进行INNER JOIN,我相信这将更加昂贵和不必要.