Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 复合键约束_Sql_Sql Server 2008_Tsql_Sql Server 2008 R2_Sql Server 2012 - Fatal编程技术网

Sql 复合键约束

Sql 复合键约束,sql,sql-server-2008,tsql,sql-server-2008-r2,sql-server-2012,Sql,Sql Server 2008,Tsql,Sql Server 2008 R2,Sql Server 2012,我正在为手袋购物网站创建一个数据库,其中有一个名为dbo.ProductMatching的表 CREATE TABLE [dbo].[ProductMatching]( [ProductMatchingID] [int] NOT NULL IDENTITY, -- This can be Made Primary Key but i want to use composite keys [MainProductID] [int] NOT NULL, [MainProductColourID] [

我正在为手袋购物网站创建一个数据库,其中有一个名为dbo.ProductMatching的表

CREATE TABLE [dbo].[ProductMatching](
[ProductMatchingID] [int] NOT NULL IDENTITY, -- This can be Made Primary Key but i want to use composite keys
[MainProductID] [int] NOT NULL,
[MainProductColourID] [int] NOT NULL,
[ReferenceProductID] [int] NULL,
[ReferenceProductColourID] [int] NOT NULL,
[CreatedOn] [datetime] NOT NULL,
[UpdatedOn] [datetime] NOT NULL
) ON [PRIMARY]
我想做的是使(MainProductID,MainProductColourID)唯一,对于每个组合,我想使(ReferenceProductID,ReferenceProductColourID)的组合也唯一

e、 g假设我有(MainProductID,mainProductColourId)=(1,1)的组合,它引用(ReferenceProductID,ReferenceProductColourID)=(2,2),那么(1,1)不能引用另一个(2,3)组合。。我不能使整个四个键组合键,因为它将允许引用(1,1)到(2,3)的组合


我知道我可以在插入数据时发出exists语句,或者发出before insert触发器或update触发器以保持数据一致性,但我想知道的是,使用组合键是否可以做到这一点。。如果没有,还有什么其他可用选项…

如果我理解这个问题,那么有两个简单的唯一约束

MainProductID,MainProductColor ID

MainProductID,ReferenceProductID

我会使用
MainProductID、MainProductColourID作为复合主键
(将满足该唯一约束)

如果这是错误的,请给出更多正确的示例

还有更多不正确的原因

不清楚您是说您知道产品和参考之间允许的匹配,还是说产品只能有0-1个链接参考?是的,匹配将手动插入。。此表用于显示与用户正在购买的产品(您也可能喜欢的产品)类似的产品。在此类似产品中,假设用户购买的是绿色手袋,在类似产品中,参考的是红色夹克,则不应再参考不同颜色的夹克(假设为黑色)。绿色手提包将显示红色夹克作为类似产品的设置将由管理员预定义…为什么要使用复合主键?您始终可以创建唯一的约束。检查:@thepirat000如果你有一个自然的复合键,为什么要浪费PK的一个单独的列?@Blam因为子表的连接条件要简单得多,DB必须维护两个索引而不是一个,它更干净、更容易维护,并且键不与业务耦合。但最后还是口味的问题。。。