gpt4 book ai didi

SQLite3 - 为什么不会删除引用数据?

转载 作者:行者123 更新时间:2023-12-03 15:39:03 24 4
gpt4 key购买 nike

我对 SQLite 真的很陌生,所以请原谅我的无知和愚蠢的错误。

简介

我目前有两张表,一张是包含公司名称的主表,第二张是与该公司相关的文章。

架构

表格1

Companies(id INTEGER PRIMARY KEY AUTO INCREMENT, tick TEXT, business_name TEXT)

表 2
Articles(id INTEGER PRIMARY KEY, 
tick TEXT, thedate TEXT, thetime TEXT, title TEXT, link TEXT,
FOREIGN KEY(tick) REFERENCES Companies(tick) ON DELETE CASCADE)

为什么这不起作用?一旦我从 Companies 中删除一个勾号表,它不会删除 Articles 中的所有项目 table 。

最佳答案

您必须 enable foreign key support对于每个数据库连接。

Assuming the library is compiled with foreign key constraints enabled, it must still be enabled by the application at runtime, using the PRAGMA foreign_keys command. For example:

sqlite> PRAGMA foreign_keys = ON;



这是一个示例 session 。注意 unique对“滴答”的约束。
sqlite> create table companies(
...> id INTEGER PRIMARY KEY AUTOINCREMENT,
...> tick TEXT unique,
...> business_name TEXT
...> );
sqlite>
sqlite> create table articles(
...> id INTEGER PRIMARY KEY,
...> tick TEXT,
...> thedate TEXT,
...> thetime TEXT,
...> title TEXT,
...> link TEXT,
...> FOREIGN KEY(tick) REFERENCES Companies(tick) ON DELETE CASCADE
...> );
sqlite>
sqlite> insert into companies values (1, 'aaa', 'AAA company');
sqlite> insert into articles values (1, 'bbb', '2014-01-01', '08:00', 'Some Title', 'some link');

该插入语句成功了,因为尽管我们声明了外键约束,但我们还没有启用它。让我们摆脱这些数据。 . .
sqlite> delete from companies;
sqlite> delete from articles;

启用外键约束。 . .
sqlite> pragma foreign_keys=on;

然后再试一次。
sqlite> insert into companies values (1, 'aaa', 'AAA company');
sqlite> insert into articles values (1, 'aaa', '2014-01-01', '08:00', 'Some Title', 'some link');
sqlite> select * from articles where tick = 'aaa';
1|aaa|2014-01-01|08:00|Some Title|some link

有我们的文章。
sqlite> delete from companies where tick = 'aaa';
sqlite> select * from articles where tick = 'aaa';
sqlite>

没有返回,因为 on delete cascade删除了引用行。

关于SQLite3 - 为什么不会删除引用数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24936251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com