【发布时间】:2011-06-11 12:59:40
【问题描述】:
我有一个带有列名 ID 的 table1,我有一个带有列名 ID 的 table2。表一中的 Id 列是主键,但在第二个表中不是,但是我想向 table1.ID 列添加一个约束,以不接受 table2.ID 以外的值。这可能吗?如果是这样,如何在 SQL Server 中完成?
【问题讨论】:
标签: sql sql-server sql-server-2005 sql-server-2008
我有一个带有列名 ID 的 table1,我有一个带有列名 ID 的 table2。表一中的 Id 列是主键,但在第二个表中不是,但是我想向 table1.ID 列添加一个约束,以不接受 table2.ID 以外的值。这可能吗?如果是这样,如何在 SQL Server 中完成?
【问题讨论】:
标签: sql sql-server sql-server-2005 sql-server-2008
是的,它是... 您必须建立一对多关系 - FOREIGN KEY 约束。
您可以通过发出 ALTER 语句来做到这一点。如果没有违反约束,则可以这样做
【讨论】:
以下是创建外键关系的示例:
create table Table1 (id int primary key)
create table Table2 (id int foreign key references Table1(id))
在数据库设计中,表 2 和表 1 之间称为“一对多”关系。表 1 中的一行可以关联表 2 中的多行。 Table1 中的一行只能与 Table2 中的一行相关。
【讨论】:
我想给 table1.ID 添加一个约束 列不接受其他值 那是table2.ID
表一中的 Id 列是主要的 键
只有在 Table2 中的 ID 列被定义为唯一或者是主键时,这才可能用于外键约束。
这将起作用:
create table Table2 (id int unique)
create table Table1 (id int primary key foreign key references Table2(id))
这也可以:
create table Table2 (id int primary key)
create table Table1 (id int primary key foreign key references Table2(id))
这不起作用:
create table Table2 (id int)
create table Table1 (id int primary key foreign key references Table2(id))
【讨论】:
您将第一个表列“ID”作为第二个表的外键。
【讨论】: