当使用sqlite3 for Python时,如何在SQL中创建主键和外键?

roejwanj  于 2022-12-23  发布在  SQLite
关注(0)|答案(1)|浏览(173)

我尝试创建两个表car_main和car_info。car_main有一个主键和一个外键,分别是car_id和model_id。car_info有两个外键,car_id和model_id。

connection = sqlite3.connect("TutorialDB.db")
crsr = connection.cursor()
sql_command = """CREATE TABLE car_main (
car_id INTEGER PRIMARY KEY,
model_id INTEGER FOREIGN KEY REFERENCES car_main(car_id),
);"""
crsr.execute(sql_command)
sql_command = """CREATE TABLE car_info (
car_id INTEGER FOREIGN KEY REFERENCES car_main(car_id),
model_id INTEGER FOREIGN KEY REFERENCES car_main(model_id),
year INTEGER,
price INTEGER,
used BOOLEAN
);"""
crsr.execute(sql_command)
connection.close()```
r7knjye2

r7knjye21#

外键语句没有意义,因为您引用的是同一个表

model_id INTEGER FOREIGN KEY REFERENCES car_main(car_id)

也许你需要

CREATE TABLE car_info (
    model_id INTEGER PRIMARY KEY,
    year INTEGER,
    price INTEGER,
    used BOOLEAN
);

CREATE TABLE car_main (
    car_id INTEGER PRIMARY KEY,
    model_id INTEGER,
    FOREIGN KEY(model_id) REFERENCES car_info(model_id)
);

相关问题