Clé Étrangère SQLite
je suis les instructions de la documentation de SQLite à http://www.sqlite.org/foreignkeys.html cependant ma tentative d'ajouter une clé étrangère échoue. Voici mes instructions de création:
CREATE TABLE
checklist (
_id INTEGER PRIMARY KEY AUTOINCREMENT,
checklist_title TEXT,
description TEXT,
created_on INTEGER,
modified_on INTEGER
);
CREATE TABLE
item (
_id INTEGER PRIMARY KEY AUTOINCREMENT,
FOREIGN KEY(checklist_id) REFERENCES checklist(_id),
item_text TEXT, item_hint TEXT,
item_order INTEGER,
created_on INTEGER,
modified_on INTEGER
);
la première table est faite fine. L'erreur se produit dans le deuxième énoncé. J'ai essayé à la fois d'emballer les deux requêtes dans une transaction et sans. Voici l'erreur:
Colonne inconnue "checklist_id" dans la définition de clé étrangère (code 1): , lors de la compilation: création d'un élément de TABLE (_id clé entière primaire auto-identification, clé étrangère(checklist_id) REFERENCES checklist(_id), item_text TEXT, item_hint TEXT, item_order INTEGER, created_on INTEGER, modified_on INTEGER)
4 réponses
vous devez encore créer la colonne avant de l'ajouter comme clé étrangère.
donc ce serait:
CREATE TABLE
checklist (
_id INTEGER PRIMARY KEY AUTOINCREMENT,
checklist_title TEXT,
description TEXT,
created_on INTEGER,
modified_on INTEGER
);
CREATE TABLE
item (
_id INTEGER PRIMARY KEY AUTOINCREMENT,
checklist_id INTEGER,
item_text TEXT,
item_hint TEXT,
item_order INTEGER,
created_on INTEGER,
modified_on INTEGER,
FOREIGN KEY(checklist_id) REFERENCES checklist(_id)
);
Simplement que vous êtes absent checklist_id colonne item tableau. Vous devez le déclarer avant de vouloir le Définir comme FOREIGN KEY. Vous avez essayé de créer FK sur la colonne non existante et c'est la raison pour laquelle cela ne fonctionne pas.
vous devez donc ajouter ceci:
checklist_id INTEGER,
FOREIGN KEY(checklist_id) REFERENCES checklist(_id)
maintenant ça devrait marcher.
vous devez inclure le nom de la colonne avant de l'envelopper avec la touche FOREIGN().
CREATE TABLE
item (
_id INTEGER PRIMARY KEY AUTOINCREMENT,
checklist_id INTEGER,
FOREIGN KEY(checklist_id) REFERENCES checklist(_id),
item_text TEXT, item_hint TEXT,
item_order INTEGER,
created_on INTEGER,
modified_on INTEGER
);
mettre la définition de clé étrangère à la fin de L'énoncé SQL