问题
I'm trying to create a foreign key on two columns of a table to point to the same column of another table, but I seem to get an error.
I'm using SQL Server with Microsoft SQL Server Management Studio.
Here's what I do:
CREATE TABLE House
(
hid INTEGER PRIMARY KEY,
hname VARCHAR(32) NOT NULL,
address VARCHAR(128) NOT NULL,
);
CREATE TABLE Room
(
sid INTEGER,
hid INTEGER FOREIGN KEY REFERENCES House(hid),
rname VARCHAR(32) NOT NULL,
CONSTRAINT sid_pk PRIMARY KEY(sid, hid)
);
CREATE TABLE Seat
(
hid INTEGER,
sid INTEGER,
plid INTEGER,
row INTEGER NOT NULL,
seat INTEGER NOT NULL,
CONSTRAINT sid_fk
FOREIGN KEY (hid, sid) REFERENCES Room(hid, sid), <-- Here's the error
CONSTRAINT plid_pk
PRIMARY KEY (hid, sid, plid),
UNIQUE(hid, sid, row, seat)
);
And I keep getting "Error 1776" saying that there is no primary key in the room-table...
回答1:
as per comments from @hogan..posting as community wiki,so that this is not lost
In the Room
table ,primary key is (sid, hid)
..But in seat
table,you are referencing a new primary key Room(hid, sid)
so change your room
table constraint definition like below
CONSTRAINT sid_fk
FOREIGN KEY (hid, sid) REFERENCES Room(sid,hid)
来源:https://stackoverflow.com/questions/41305693/sql-server-adding-foreign-key-on-multiple-columns