简体   繁体   中英

Trouble with composite foreign keys in sqlite3

there! I have a failing foreign key constraint in sqlite3 and I really have no idea why. I'm using a composite foreign key as discribed here ( http://www.sqlite.org/foreignkeys.html#fk_composite ) and a "normal" foreign key.

Here are my schemas:

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

Here is the data the foreign key is referring to:

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

And here is my insert:

sqlite> INSERT INTO alias_source_relations VALUES(1, 1, 'Allen1980');
Error: foreign key constraint failed

Does anyone know what I am missing? Thanks for your help!

Regards, Marian

检查列顺序!

INSERT INTO alias_source_relations VALUES('Allen1980', 1, 1);

It's safer and also more descriptive to include the column names:

INSERT INTO alias_source_relations (source_id, author_id, alias_id)
    VALUES ('Allen1980', 1, 1);

Like this, someone who does not know the table schema by heart still understands the command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM