【问题标题】:Foreign key mismatch when insert (SQLite)插入时外键不匹配(SQLite)
【发布时间】:2020-02-20 00:29:43
【问题描述】:

这是我的 sqlite 代码..

CREATE TABLE "performance" (
    "title" TEXT,
    "date"  date,
    "theaterID" INTEGER,    

PRIMARY KEY("title","date","theaterID"),

    FOREIGN KEY("title") REFERENCES "movies"("title"),
    FOREIGN KEY("theaterID") REFERENCES "theater"("theaterID")
);

CREATE TABLE "reservation" (
    "userName"  TEXT,
    "reservationID" INTEGER auto_increment,
    "date"  date,
    "theaterID" INTEGER,
    PRIMARY KEY("userName","reservationID","date","theaterID"),
    FOREIGN KEY("date") REFERENCES "performance"("date"),
    FOREIGN KEY("userName") REFERENCES "user"("userName"),
    FOREIGN KEY("theaterID") REFERENCES "theater"("theaterID")
);

我按特定顺序进行以下插入:

INSERT INTO performance(title,date,theaterID) 
VALUES("The Godfather", 20200230, 9);



INSERT INTO reservation(userName,reservationID,date,theaterID)
VALUES("user1", 1 , 20200230, 9);

在我尝试插入预订之前,一切正常。我收到以下错误:

“外键不匹配错误 - 'reservation' 引用 'performance'”

我似乎找不到原因?我需要做哪些改变?

【问题讨论】:

  • 我已经坐在这里几个小时无法找到解决方案.. 非常感谢您的回答

标签: sql database sqlite foreign-keys


【解决方案1】:

你有:

FOREIGN KEY("date") REFERENCES "performance"("date"),

但是,performance 的主键包含三个部分:

PRIMARY KEY("title", "date", "theaterID"),

您需要在外键声明中以正确的顺序引用所有三个:

FOREIGN KEY("date") REFERENCES "performance"("title", "date", "theaterID"),

但是,"title" 不在表格中,因此您必须添加它。

或者,只需向"performance" 添加一个自动递增的主键并将其用作参考。

另外,去掉双引号。它们只是让 SQL 更难写和读。而且答案更难写。

【讨论】:

    【解决方案2】:

    查看这篇文章 What is causing Foreign Key Mismatch error?

    问题可能是:

    • 在外键约束中命名的父键列不是 父表的主键,不具有唯一性 使用 CREATE TABLE 中指定的整理顺序进行约束

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      相关资源
      最近更新 更多