有!我在sqlite3中有一个失败的外键约束,我真的不知道为什么。我使用了这里描述的复合外键(http://www.sqlite.org/foreignkeys.html#fk_composite)和"正常"外键。
以下是我的架构:
sqlite> .schema sources
CREATE TABLE sources(
source_id VARCHAR(16) NOT NULL,
source_type INTEGER NOT NULL,
title VARCHAR(128) NOT NULL,
year INTEGER,
month INTEGER,
PRIMARY KEY(source_id),
UNIQUE(title)
);
sqlite> .schema author_aliases
CREATE TABLE author_aliases(
author_id INTEGER NOT NULL,
alias_id INTEGER NOT NULL,
forenames VARCHAR(128),
surname VARCHAR(128) NOT NULL,
PRIMARY KEY(author_id, alias_id),
FOREIGN KEY(author_id) REFERENCES authors(author_id),
UNIQUE(forenames, surname)
);
sqlite> .schema alias_source_relations
CREATE TABLE alias_source_relations(
source_id VARCHAR(16) NOT NULL,
author_id INTEGER NOT NULL,
alias_id INTEGER NOT NULL,
PRIMARY KEY(source_id, author_id, alias_id),
FOREIGN KEY(source_id) REFERENCES sources(source_id),
FOREIGN KEY(author_id, alias_id) REFERENCES author_aliases(author_id, alias_id)
);
以下是外键所指的数据:
sqlite> SELECT * FROM sources WHERE source_id='Allen1980';
Allen1980|0|The definition of electronegativity and the chemistry of the noble gases|1980|
sqlite> SELECT * FROM author_aliases WHERE author_id=1 and alias_id=1;
1|1|Leland C.|Allen
sqlite> SELECT * FROM authors WHERE author_id=1;
1|Leland Cullen|Allen
这是我的插页:
sqlite> INSERT INTO alias_source_relations VALUES(1, 1, 'Allen1980');
Error: foreign key constraint failed
有谁知道我错过了什么?谢谢你的帮助!
此致 玛丽安
答案 0 :(得分:4)
检查列顺序!
INSERT INTO alias_source_relations VALUES('Allen1980', 1, 1);
答案 1 :(得分:3)
包含列名称更安全,更具描述性:
INSERT INTO alias_source_relations (source_id, author_id, alias_id)
VALUES ('Allen1980', 1, 1);
像这样,不了解表格架构的人仍然理解命令。