Kai*_*ran 7 sql sql-server foreign-keys sql-server-2008 composite-primary-key
如果我声明下面的表是否隐含暗示外键都是唯一的主键,还是我需要做更多的事情才能将这两个属性作为主键?
CREATE TABLE Report_has_Items
(
ReportID int REFERENCES Report(ReportID) NOT NULL,
ItemID int REFERENCES Item(ItemID) NOT NULL
)
Run Code Online (Sandbox Code Playgroud)
基本上这两个属性都是来自其他表的外键,它们一起形成一个唯一的键.
gts*_*ouk 11
不,不.上表没有主键.如果要将字段用作主键,请使用:
CREATE TABLE Report_has_Items(
ReportID int REFERENCES Report(ReportID) NOT NULL,
ItemID int REFERENCES Item(ItemID) NOT NULL,
PRIMARY KEY (ReportID, ItemID)
)
Run Code Online (Sandbox Code Playgroud)
或类似的东西取决于你的sql dilect.
让我们说出我们的约束,呃?
CREATE TABLE dbo.Report_has_Items(
ReportID int NOT NULL,
CONSTRAINT [FK_RHI_Report] (ReportId) REFERENCES dbo.Report(ReportID),
ItemID int NOT NULL,
Constraint [FK_RHI_Item] (ItemId) REFERENCES dbo.Item(ItemID),
CONSTRAINT [PK_RHI] PRIMARY KEY (ReportID, ItemID)
)
Run Code Online (Sandbox Code Playgroud)