简体   繁体   中英

SQL Multiple Foreign Keys as Primary Keys

If I declare the table below does it implicitly imply that both the foreign keys make a unique primary key or do I need to do something more to make both attributes as a primary key?

CREATE TABLE Report_has_Items
(
    ReportID int REFERENCES Report(ReportID) NOT NULL,
    ItemID int REFERENCES Item(ItemID) NOT NULL
)

Essentially both attributes which are foreign keys from other tables, together would form a unique key.

No it doesn't. The above table has no primary key. If you want to use the fields as a primary key use:

CREATE TABLE Report_has_Items(
    ReportID int REFERENCES Report(ReportID) NOT NULL,
    ItemID int REFERENCES Item(ItemID) NOT NULL,
    PRIMARY KEY (ReportID, ItemID)
)

or something similar depending on your sql dilect.

Let's name our constraints, eh?

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)
)

I am not sure i understand your question completely but i assume you are trying to create a composite primary key (primary key with more than one attribute). You could do the following.

CREATE TABLE Report_has_Items(
  ReportID int references Report(ReportID),
  ItemID int references Item(ItemID),
  PRIMARY KEY (ReportID , ItemID )
);

Note :The pair (ReportID , ItemID ) must then be unique for the table and neither value can be NULL.

Here is a very useful link for SQL Queries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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