How do I make two foreign keys a primary key?

106 views Asked by At

My table MealIng has two foreign keys from two other tables that I want to make primary key. How do I specify this?

This is my code. What do I need to change to get this to work?

CREATE TABLE Meals (
    MealID INTEGER PRIMARY KEY,
    Meal TEXT,
    Type TEXT
);

CREATE TABLE Ing (
    IngID INTEGER PRIMARY KEY,
IngName TEXT,
    UnitCost NUMERIC
);

CREATE TABLE MealIng (
MealID INTEGER FOREIGN KEY REFERENCES Meal(MealID),
    IngID INTEGER FOREIGN KEY REFERENCES Ing(IngID),
    Quantity INTEGER
);
1

There are 1 answers

2
David Browne - Microsoft On

Like this:

CREATE TABLE MealIng 
(
    MealID INTEGER NOT NULL FOREIGN KEY REFERENCES Meal(MealID),
    IngID INTEGER NOT NULL FOREIGN KEY REFERENCES Ing(IngID),
    Quantity INTEGER,
    CONSTRAINT PK_MealIng PRIMARY KEY (MealId, IngId),
    INDEX IX_MealIng_IngID (IngID)
)

See the <table_constraint> section in CREATE TABLE (Transact-SQL)

And you generally want an index supporting each foreign key for lookups and cascading deletes. The PK supports the MealID FK, but you need a secondary index to support the IngID FK.