外键字段可以具有唯一值吗 [英] can foreign key field have a unique value

查看:155
本文介绍了外键字段可以具有唯一值吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有一个主键的表

i have one table having one primary key

create table PSM.dbo.Prospect(Prospect_ID int primary key,Prospect_Name varchar(50),Prospect_Source varchar(50),Prospect_Products_Services varchar(50) );



第二个表具有外键和一个主键



2nd table having foreign key and one primary key

create table PSM.dbo.conversion(Prospect_ID int references Prospect(Prospect_ID)  ,Customer_ID int primary key,Customer_Name varchar(50),Customer_Products_Services varchar(50));




现在我希望具有propect_id的第二个表也应该具有唯一值(不重复).所以我可以这样做吗?




now i want 2nd table having propect_id should also have unique value(no duplication).so hw can i do this

推荐答案

在第二个字段上设置唯一约束桌子.因此,即使它将是外键,该约束也将确保在插入时不会发生重复.任何重复都会引发约束错误.

在这里阅读:
http://msdn.microsoft.com/en-us/library/ms191166.aspx [ ^ ]
http://msdn.microsoft.com/en-us/library/aa933091%28v = sql.80%29.aspx [ ^ ]
http://www.w3schools.com/sql/sql_unique.asp [
Put a unique constraint on that field of the 2nd table. Thus, even though it will be a Foreign Key, the constraint will make sure that no duplication happens at the time of insertion. Any repeat would throw a constraint error.

Read here:
http://msdn.microsoft.com/en-us/library/ms191166.aspx[^]
http://msdn.microsoft.com/en-us/library/aa933091%28v=sql.80%29.aspx[^]
http://www.w3schools.com/sql/sql_unique.asp[^]


为其添加唯一键

Add a Unique key to it

ALTER TABLE PSM.dbo.conversion
ADD UNIQUE (propect_id)



希望对您有帮助.......



Hope it helps.......


这篇关于外键字段可以具有唯一值吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆