【问题标题】:How to find all references of a particular primary key in a sqlite table?如何在 sqlite 表中查找特定主键的所有引用?
【发布时间】:2012-08-28 06:07:14
【问题描述】:

我已设置PRAGMA foreign_keys=ON;

我正在尝试删除 sqlite3 表中的一些记录,它显示 Error: constraint failed

sqlite> delete from auth_user where id = 110;
Error: constraint failed

如果PRAGMA foreign_keys 关闭,它会起作用。数据库有很多表,错误很模糊。如果我们尝试删除,我认为其他数据库系统会列出引用主键的表。

我可以找到引用该特定主键 id=110 的所有表的有效方法是什么?

架构:

CREATE TABLE "auth_user" (
    "id" integer NOT NULL PRIMARY KEY,
    "username" varchar(30) NOT NULL UNIQUE,
    "first_name" varchar(30) NOT NULL,
    "last_name" varchar(30) NOT NULL,
    "email" varchar(75) NOT NULL,
    "password" varchar(128) NOT NULL,
    "is_staff" bool NOT NULL,
    "is_active" bool NOT NULL,
    "is_superuser" bool NOT NULL,
    "last_login" datetime NOT NULL,
    "date_joined" datetime NOT NULL
);

【问题讨论】:

    标签: database sqlite foreign-keys primary-key constraints


    【解决方案1】:

    我认为使用 SQLite 列出外键约束没有明确的方法。但是,您可以列出所有具有此类约束的表,如下所示。然后您可以解析返回的 SQL 以找到约束。

    假设你有两个父子表:

    sqlite> PRAGMA foreign_keys=ON;
    sqlite> create table Parent (
       ...>     Id INTEGER PRIMARY KEY AUTOINCREMENT, 
       ...>     foo TEXT);
    sqlite> create table Child (
       ...>     Id INTEGER PRIMARY KEY AUTOINCREMENT, 
       ...>     ParentId INTEGER NOT NULL, 
       ...>     bar TEXT,
       ...>     FOREIGN KEY (ParentId) REFERENCES Parent(Id));
    

    您可以列出具有外键的CREATE TABLE 语句:

    sqlite> SELECT sql FROM sqlite_master WHERE sql LIKE '%REFERENCES%';
    CREATE TABLE Child (
        Id INTEGER PRIMARY KEY AUTOINCREMENT, 
        ParentId INTEGER NOT NULL, 
        bar TEXT,
        FOREIGN KEY (ParentId) REFERENCES Parent(Id))
    

    您可能已经知道这一点,但是在关闭外键时删除受某些外键约束的行会破坏数据库的引用完整性,因此我只能建议您不要这样做。

    【讨论】:

    • 哦.. 我不知道 sqlite_master。我使用 bash 脚本解析了模式。无论如何,谢谢。
    猜你喜欢
    • 2021-11-16
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 2018-01-09
    • 2021-07-10
    • 2021-07-11
    相关资源
    最近更新 更多