SQLite外键不匹配错误

use*_*960 14 sqlite

为什么在执行下面的脚本时出现SQLite" 外键不匹配 "错误?

DELETE 
FROM rlsconfig 
WHERE importer_config_id=2 and 
program_mode_config_id=1
Run Code Online (Sandbox Code Playgroud)

这是主表定义:

 CREATE TABLE [RLSConfig] (
        "rlsconfig_id"      integer PRIMARY KEY AUTOINCREMENT NOT NULL,
        "importer_config_id"        integer NOT NULL,
        "program_mode_config_id"        integer NOT NULL,
        "l2_channel_config_id"      integer NOT NULL,
        "rls_fixed_width"       integer NOT NULL
    ,
        FOREIGN KEY ([importer_config_id])
            REFERENCES [ImporterConfig]([importer_config_id]),
        FOREIGN KEY ([program_mode_config_id])
            REFERENCES [ImporterConfig]([importer_config_id]),
        FOREIGN KEY ([importer_config_id])
            REFERENCES [ImporterConfig]([program_mode_config_id]),
        FOREIGN KEY ([program_mode_config_id])
            REFERENCES [ImporterConfig]([program_mode_config_id])
    )
Run Code Online (Sandbox Code Playgroud)

和引用表:

    CREATE TABLE [ImporterConfig] (
        "importer_config_id"        integer NOT NULL,
        "program_mode_config_id"        integer NOT NULL,
        "selected"      integer NOT NULL DEFAULT 0,
        "combined_config_id"        integer NOT NULL,
        "description"       varchar(50) NOT NULL COLLATE NOCASE,
        "date_created"      datetime NOT NULL DEFAULT (CURRENT_TIMESTAMP),
        PRIMARY KEY ([program_mode_config_id], [importer_config_id])
    ,
        FOREIGN KEY ([program_mode_config_id])
            REFERENCES [ProgramModeConfig]([program_mode_config_id])
    )
Run Code Online (Sandbox Code Playgroud)

小智 41

在具有复合主键的表上使用外键时,必须使用复合外键以及所引用表的主键中的所有字段.

例:

CREATE TABLE IF NOT EXISTS parents
(
    key1 INTEGER NOT NULL,
    key2 INTEGER NOT NULL,
    not_key INTEGER DEFAULT 0,

    PRIMARY KEY ( key1, key2 )
);


CREATE TABLE IF NOT EXISTS childs
(
    child_key INTEGER NOT NULL,
    parentKey1 INTEGER NOT NULL,
    parentKey2 INTEGER NOT NULL,
    some_data INTEGER,

    PRIMARY KEY ( child_key ),
    FOREIGN KEY ( parentKey1, parentKey2 ) REFERENCES parents( key1, key2 )
);
Run Code Online (Sandbox Code Playgroud)


Vin*_*nay 11

我不确定SQLite.但我在谷歌上发现了这个链接.http://www.sqlite.org/foreignkeys.html.一些原因可以

  • 父表不存在,或
  • 外键约束中指定的父键列不存在,或
  • 外键约束中指定的父键列不是父表的主键,并且不受使用CREATE TABLE中指定的整理顺序的唯一约束的约束,或者
  • 子表引用父级的主键而不指定主键列,父级中的主键列数与子键列的数量不匹配.


Noa*_*oah 5

不幸的是,SQLite 一直给出这个错误,而没有提到哪个外键约束失败了。您只能尝试一一检查它们,这通常不起作用,然后在没有约束的情况下重建表并将它们一一添加回来,直到找到问题为止。SQLite 在很多方面都很棒,但这不是其中之一。