如何使用引用复合主键的复合外键将行插入 table

How to insert a row into a table with a composite foreign key referencing a composite primary key

我有一个 table 叫 BB:

CREATE TABLE BB (
    SID INTEGER PRIMARY KEY,
    FName TEXT,
    LName TEXT
);

还有一个名为 QR 的 table,它包含一个引用 BB table 上的 FName 和 LName 行的复合外键 table。

CREATE TABLE QR (
    QID INTEGER PRIMARY KEY AUTOINCREMENT,
    FName TEXT,
    LName TEXT,
    DateTime_IN TEXT,
    Sid4 INTEGER,
    Mode TEXT,
    FOREIGN KEY (FName, LName) REFERENCES BB (FName, LName)
);

BB table 填充了以下数据:

INSERT INTO BB (SID, FName, LName) VALUES
(12345678, "R", "B"),
(23456789, "X", "C"),
(34567890, "M", "S"),
(45678901, "Z", "H"),
(56789012, "T", "A"),
(67890123, "N", "F"),
(78901234, "H", "M"),
(89012345, "A", "S"),
(90123456, "F", "F"),
(12345677, "M", "M");

并且需要将此数据插入二维码table:

INSERT INTO QR
(FName, LName, DateTime_IN, Sid4, Mode)
VALUES
("R", "B", "2021-08-10 14:00:02", 12345678, "ZOOM"),
("X", "C", "2021-08-10 14:00:02", 23456789, "ZOOM"),
("M", "S", "2021-08-10 14:00:03", 34567890, "ZOOM"),
("Z", "H", "2021-08-10 15:01:01", 45678901, "ZOOM"),
("T", "A", "2021-08-10 14:01:01", 56789012, "ZOOM"),
("N", "F", "2021-08-10 14:02:02", 67890123, "ZOOM"),
("H", "M", "2021-08-10 14:03:03", 78901234, "ZOOM"),
("A", "S", "2021-08-11 14:04:04", 89012345, "ZOOM");

但是当我在数据库浏览器中 运行 它时,我得到这个错误:

Execution finished with errors.
Result: foreign key mismatch - "QR" referencing "BB"
At line 1:
INSERT INTO QR
(FName, LName, DateTime_IN, Sid4, Mode)
VALUES
("R", "B", "2021-08-10 14:00:02", 12345678, "ZOOM"),
("X", "C", "2021-08-10 14:00:02", 23456789, "ZOOM"),
("M", "S", "2021-08-10 14:00:03", 34567890, "ZOOM"),
("Z", "H", "2021-08-10 15:01:01", 45678901, "ZOOM"),
("T", "A", "2021-08-10 14:01:01", 56789012, "ZOOM"),
("N", "F", "2021-08-10 14:02:02", 67890123, "ZOOM"),
("H", "M", "2021-08-10 14:03:03", 78901234, "ZOOM"),
("A", "S", "2021-08-11 14:04:04", 89012345, "ZOOM");

为什么它不让我插入这些数据。所有数据都是正确的并且与 BB table 匹配。我在 DB Browser

中使用 SQLite 版本 3.34.1

您的代码的问题在于父 table BBFNameLName 的组合未定义为 UNIQUE
有了这个变化:

CREATE TABLE BB (
    SID INTEGER PRIMARY KEY,
    FName TEXT,
    LName TEXT, 
    UNIQUE(FName, LName)
);

work as it should.

但是,根据您的情况,正确的设计是在 QR 中定义一个引用 BBSID 列的整数列,而不是复合外键:

CREATE TABLE QR (
    QID INTEGER PRIMARY KEY AUTOINCREMENT,
    SID INTEGER REFERENCES BB (SID),
    DateTime_IN TEXT,
    Sid4 INTEGER,
    Mode TEXT
);