SQLite外键不匹配错误

时间:2011-07-27 17:26:02

标签: sqlite

为什么我在执行下面的脚本时遇到SQLite“外键不匹配”错误?

DELETE 
FROM rlsconfig 
WHERE importer_config_id=2 and 
program_mode_config_id=1

这是主表定义:

 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])
    )

并引用了表格:

    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])
    )

3 个答案:

答案 0 :(得分:37)

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

示例:

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 )
);

答案 1 :(得分:10)

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

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

答案 2 :(得分:4)

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

相关问题