简体   繁体   English

如何使用2个外键相互关联2个表

[英]How to Relate 2 table with each other with 2 foreign keys

Here is my code it generates Foreign key conflict error 这是我的代码,它生成外键冲突错误

CREATE TABLE tblProducts
(
ProductID int NOT NULL IDENTITY PRIMARY KEY,
ProductName nvarchar(30) NOT NULL,
BatchID int NOT NULL FOREIGN KEY REFERENCES tblBatches (BatchID)
)

CREATE TABLE tblBatches
(
BatchID INT NOT NULL IDENTITY PRIMARY KEY,
BatchCode nvarchar(20) NOT NULL,
Quantity int NOT NULL,
BatchMnf Date NOT NULL,
BatchExp Date NOT NULL,
PurchaseRate int NOT NULL,
SalesRate int NOT NULL,
ProductID int NOT NULL FOREIGN KEY REFERENCES tblProducts (ProductID)
)

You cannot do that. 你不能这样做。 This is a circular reference. 这是一个循环参考。

This is a bad design but if you want to do that, you need to make foreign key columns Nullable. 这是一个糟糕的设计,但是如果要这样做,则需要使外键列为Nullable。

CREATE TABLE tblProducts
(
ProductID int NOT NULL IDENTITY PRIMARY KEY,
ProductName nvarchar(30) NOT NULL,
BatchID int NULL FOREIGN KEY REFERENCES tblBatches (BatchID)
)

CREATE TABLE tblBatches
(
BatchID INT NOT NULL IDENTITY PRIMARY KEY,
BatchCode nvarchar(20) NOT NULL,
Quantity int NOT NULL,
BatchMnf Date NOT NULL,
BatchExp Date NOT NULL,
PurchaseRate int NOT NULL,
SalesRate int NOT NULL,
ProductID int NULL FOREIGN KEY REFERENCES tblProducts (ProductID)
)

Then you need to update reference fields after inserting records in tblBatches and tblProducts. 然后,在将记录插入到tblBatches和tblProducts中之后,需要更新参考字段。


The good design says you need to create a bridge table like this: 好的设计表明您需要创建一个像这样的桥表:

CREATE TABLE tblProductsBatch
(
ID int NOT NULL IDENTITY PRIMARY KEY,
ProductID int NOT NULL,
BatchID int NOT NULL
)

And after inserting product and batch, you need to insert a record in this table to link rows to each other. 在插入产品和批次之后,您需要在该表中插入一条记录以将行彼此链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM