我正在尝试引用两个单独的表来创建第三个表,但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)""")
答案 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)""")