我知道这是第一个标准问题,但有人问我,但我无法给他适当的答案。有两个表在.Employee 表中Employee,Technology
保存了多对多关系,其中包含字段,其中技术具有字段,
这两个表允许名称重复。我应该定义哪个唯一约束以允许唯一条目?employee_technology_rel
emp_id (auto_increment)
emp_name(varchar)
DOB (date)
tech_id(auto_increment)
tech_name(varchar)
3 回答
You can define the unique entry on table employee_technology_rel
,
ALTER TABLE employee_technology_rel
ADD CONSTRAINT emptech_pk PRIMARY KEY (emp_id, tech_id)
// or if you have set a primary key already, you can still define via UNIQUE
ALTER TABLE employee_technology_rel
ADD CONSTRAINT emptech_uq UNIQUE (emp_id, tech_id)
what it does is it only allows unique technology for every employee.
in order for you to have unique emp_name
on table Employee
as well as unique tech_name
on table Technology
, you can also alter the table by adding unique constraint
ALTER TABLE Employee ADD CONSTRAINT emp_uq UNIQUE (emp_name)
ALTER TABLE Technology ADD CONSTRAINT tech_uq UNIQUE (tech_name)
You want a composite primary key defined on the two columns in employee_technology_rel: emp_id and tech_id.
唯一索引和唯一约束相同。他们达到相同的目标。两者的 SQL 性能相同。
添加唯一约束 ALTER TABLE dbo。在 [PRIMARY] 上添加约束唯一非聚集 ( )
在 dbo 上添加唯一索引 CREATE UNIQUE NONCLUSTERED INDEX。( ) 开 [主要]
来源sqlauthority.com和msdn来自 Google 搜索:“ SQL 服务器唯一索引”。