I know it's first std question but someone asked me, but i was unable give him apropriate answer. There are two tables Employee,Technology
having many to many relation saved in employee_technology_rel
.Employee table having fields- emp_id (auto_increment)
, emp_name(varchar)
, DOB (date)
where Technology having fields tech_id(auto_increment)
, tech_name(varchar)
these two tables allows duplication of names.which unique constraint should i define for allowing unique entry?
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)
您需要在employee_technology_rel的两列上定义一个组合主键:emp_id和tech_id。
Unique Index and Unique Constraint are the same. They achieve same goal. SQL Performance is same for both.
Add Unique Constraint ALTER TABLE dbo. ADD CONSTRAINT UNIQUE NONCLUSTERED ( ) ON [PRIMARY]
Add Unique Index CREATE UNIQUE NONCLUSTERED INDEX ON dbo. ( ) ON [PRIMARY]
Source sqlauthority.com and msdn from Google search: " SQL server unique index ".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.