我有2个表,一个用于员工,一个用于部门。一名员工只能在一个部门工作,但一个部门可以有多名员工。我在它们之间添加了一个外键约束,但如果我尝试将相同的数据添加到同一个部门,那么查询将执行而不是失败。
create table Department(id int primary key auto_increment, name varchar(100));
create table Employee(id int primary key auto_increment,
department_id int not null,
name varchar(100),
foreign key (department_id) references department(id));
INSERT INTO Department(name) VALUES('China');
INSERT INTO Department(name) VALUES('England');
INSERT INTO Employee(department_id,name) VALUES (1,'Mark');
INSERT INTO Employee(department_id,name) VALUES (1,'Mark');
第二次插入后,员工'马克',我期待一个错误,但总是执行查询。如何限制某个特定员工只能在一个部门工作?
答案 0 :(得分:1)
这是因为Name列没有约束。
添加唯一约束Employee.name。
例如
ALTER TABLE Employee
ADD CONSTRAINT UC_Person UNIQUE (name)
,
答案 1 :(得分:1)
您需要(Position
,department_id
)上的唯一索引。
这仍然允许在其他部门内使用名称标记。
name
<强>查询强>
ALTER TABLE `employee` ADD UNIQUE INDEX `unique_department_id__name` (`department_id`, `name`);
<强>结果强>
INSERT INTO Employee(department_id,NAME) VALUES (1,'Mark');
INSERT INTO Employee(department_id,NAME) VALUES (1,'Mark');
<强> EDITED 强>
<强>查询强>
Query: INSERT INTO Employee(department_id,name) VALUES (1,'Mark')
1 row(s) affected
Execution Time : 0.013 sec
Transfer Time : 0 sec
Total Time : 0.014 sec
-----------------------------------------------------------
Query: INSERT INTO Employee(department_id,name) VALUES (1,'Mark')
Error Code: 1062
Duplicate entry '1-Mark' for key 'unique_department_id__name'
Execution Time : 0 sec
Transfer Time : 0 sec
Total Time : 0.003 sec
<强>结果强>
INSERT INTO Employee(department_id,NAME) VALUES (2,'Mark');