简体   繁体   English

SQL Server:在多个列上添加外键

[英]SQL Server: adding foreign key on multiple columns

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. 我正在使用SQL Server和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... 我一直得到“错误1776”说房间表中没有主键......

as per comments from @hogan..posting as community wiki,so that this is not lost 根据来自@ hogan的帖子,将其作为社区维基,这样就不会丢失

In the Room table ,primary key is (sid, hid) ..But in seat table,you are referencing a new primary key Room(hid, sid) Room表中,主键是(sid, hid) ..但是在seat表中,您正在引用一个新的主键Room(hid, sid)

so change your room table constraint definition like below 所以改变你的room表约束定义,如下所示

CONSTRAINT sid_fk FOREIGN KEY (hid, sid) REFERENCES Room(sid,hid)

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

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