#1215 SQL无法添加外键约束错误

时间:2014-09-28 20:46:49

标签: sql sql-server

这是我的代码。我无法弄清楚为什么我无法添加约束。

Create table customer(
    UserId Integer
)

CREATE TABLE Date(
    DateID      INTEGER,
    User1ID     INTEGER NOT NULL,
    User2ID     INTEGER NOT NULL,
    Date        CHAR(20) NOT NULL,
    GeoLocation CHAR(20) NOT NULL,
    BookingFee  INTEGER NOT NULL,
    CustomerRepresentative  CHAR(20) NOT NULL,
    Comments    CHAR(200),
    User1Ratings    CHAR(20),
    User2Ratings    CHAR(20),
    Primary Key (DateID),
    Check ( User1Ratings IN (‘Excellent’, ‘VeryGood’, ‘Good’, ‘Fair’, ‘Poor’) ),
    Check ( User2Ratings IN (‘Excellent’, ‘VeryGood’, ‘Good’, ‘Fair’, ‘Poor’) ),
    FOREIGN KEY (User1ID) REFERENCES customer(UserID)
)

1 个答案:

答案 0 :(得分:3)

该行为最可能的解释是UserID列未定义为customer表中的PRIMARY KEY或UNIQUE KEY

对此的一个解决方法是重新编写customer

的创建

对于SQL Server:

CREATE TABLE customer
( UserId Integer NOT NULL
, CONSTRAINT PK_customer PRIMARY KEY CLUSTERED (UserId)
);

对于MySQL:

CREATE TABLE customer
( UserId INTEGER NOT NULL PRIMARY KEY 
);