是的,您可以,无需添加新列。您必须小心正确地执行此操作以避免损坏数据库,因此在尝试此操作之前应完全备份您的数据库。
对于您的具体示例:
CREATE TABLE child(
id INTEGER PRIMARY KEY,
parent_id INTEGER,
description TEXT
);
--- create the table we want to reference
create table parent(id integer not null primary key);
--- now we add the foreign key
pragma writable_schema=1;
update SQLITE_MASTER set sql = replace(sql, 'description TEXT)',
'description TEXT, foreign key (parent_id) references parent(id))'
) where name = 'child' and type = 'table';
--- test the foreign key
pragma foreign_keys=on;
insert into parent values(1);
insert into child values(1, 1, 'hi'); --- works
insert into child values(2, 2, 'bye'); --- fails, foreign key violation
或更笼统地说:
pragma writable_schema=1;
// replace the entire table's SQL definition, where new_sql_definition contains the foreign key clause you want to add
UPDATE SQLITE_MASTER SET SQL = new_sql_definition where name = 'child' and type = 'table';
// alternatively, you might find it easier to use replace, if you can match the exact end of the sql definition
// for example, if the last column was my_last_column integer not null:
UPDATE SQLITE_MASTER SET SQL = replace(sql, 'my_last_column integer not null', 'my_last_column integer not null, foreign key (col1, col2) references other_table(col1, col2)') where name = 'child' and type = 'table';
pragma writable_schema=0;
无论哪种方式,您都可能希望在进行任何更改之前先查看 SQL 定义是什么:
select sql from SQLITE_MASTER where name = 'child' and type = 'table';
如果您使用 replace() 方法,您可能会发现在执行之前先通过运行来测试您的 replace() 命令会很有帮助:
select replace(sql, ...) from SQLITE_MASTER where name = 'child' and type = 'table';