简体   繁体   中英

sqlite3 inserting primary key data from one table into another

I have three tables: books, chapters, concepts.

I want the book_id columns to be the same in the books and chapters tables.

I inserted data into books table and then I inserted data into chapters table, but the book_id column in chapters table is empty.

How do I make these tables relational?

books table

    book_id integer,
    title text,
    PRIMARY KEY (book_id)

chapters table

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

concepts table

    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)")

There may be a bit of a misunderstanding with the concept of a foreign key here.

A foreign key is a reference to another row of a table. While a Primary Key will auto index, a Foreign Key does not. A foreign key is something you have to insert yourself; after all, you are defining the relation.

To achieve what you want, you will need get the inserted book id from the first query, and manually insert the retrieved value. This can be achieved using SQLite's last_insert_rowid() function. You would then fetch the result from the cursor. Here's an example of how you would accomplish this in 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) + ")") 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM