sqlite3将主键数据从一个表插入另一个表

时间:2017-08-30 19:17:21

标签: python sqlite

我有三张桌子:书籍,章节,概念。

我希望book_id列在书籍和章节表格中相同。

我将数据插入books表中,然后将数据插入到章节表中,但章节表中的book_id列为空。

如何使这些表成为关系?

书籍表

    book_id integer,
    title text,
    PRIMARY KEY (book_id)

章节表

    chapter_id integer,
    chapter text,
    book_id integer,
    PRIMARY KEY (chapter_id),
    FOREIGN KEY (book_id) REFERENCES books (book_id))'''

概念表

    concepts_id integer,
    concept text,
    definition text,
    chapter_id integer,
    PRIMARY KEY (concepts_id),
    FOREIGN KEY (chapter_id) REFERENCES chapters (chapter_id)

INSERT

cur.execute("INSERT INTO books (title) VALUES ('Intro to Econ.')")

cur.execute("INSERT INTO chapters (chapter) VALUES (1)")

1 个答案:

答案 0 :(得分:2)

这里可能存在对外键概念的一些误解。

外键是表的另一行的引用。虽然主键将自动索引,但外键不会。外键是你必须自己插入的东西;毕竟,你正在定义这种关系。

要实现您想要的功能,您需要从第一个查询中获取插入的书籍ID,然后手动插入检索到的值。这可以使用SQLite的last_insert_rowid()函数来实现。然后,您将从光标中获取结果。以下是如何在Python中完成此任务的示例:

#First, we add the SELECT last_insert_rowid() into the query; this is an SQLite function so it goes in the query not in the Python code.
cur.execute("INSERT INTO books (title) VALUES ('Intro to Econ.'); SELECT last_insert_rowid();") 

#Get the first column of the first row; in our case, only one column is actually returned anyway.
book_id = cur.fetchone()[0] 

#As you can see, we are now inserting the book_id ourselves. Foreign Keys do not auto index, so we need to relate the tables ourselves.
cur.execute("INSERT INTO chapters (chapter, book_id) VALUES (1, " + str(book_id) + ")")