引用不在SQL中工作的外键

时间:2015-11-21 20:22:38

标签: python sql sqlite

我正在尝试引用两个单独的表来创建第三个表,但SQL说FOREIGN附近有语法错误

import sqlite3 as db
connection = db.connect("doctor_who_database")

cursor = connection.cursor()

cursor.execute("""CREATE TABLE IF NOT EXISTS doctor_who_database(
item_id TEXT PRIMARY KEY,
item TEXT)""")

cursor.execute("""CREATE TABLE IF NOT EXISTS doctor_who_database2(
person_id TEXT PRIMARY KEY,
season TEXT,
person TEXT)""")



cursor.execute("""CREATE TABLE IF NOT EXISTS doctor_who_database3(
id TEXT PRIMARY KEY,
item TEXT,
season TEXT,
person TEXT)""")

cursor.execute("""FOREIGN KEY(item_id) REFERENCES doctor_who_database(item_id)""")

1 个答案:

答案 0 :(得分:2)

FOREIGN KEY中的字段必须出现在创建FK的表中,item_id不是doctor_who_database3中的字段,FOREIGN KEY也不是命令本身,它应该放在CREATE TABLE中,例如

cursor.execute("""CREATE TABLE IF NOT EXISTS doctor_who_database3(
id TEXT PRIMARY KEY,
item TEXT,
season TEXT,
person TEXT,
FOREIGN KEY(id) REFERENCES doctor_who_database(item_id)""")