如何插入两个相关联的表foreign_keys?

How to insert into two tables that are both related together with foreign_keys?

这是我的 table:

CREATE TABLE thread
(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT,
    post_id INTEGER,
    FOREIGN KEY(post_id) REFERENCES post(id)
);

CREATE TABLE post
(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    message TEXT,
    thread_id INTEGER,
    user_id INTEGER,
    FOREIGN KEY(thread_id) REFERENCES thread(id),
    FOREIGN KEY(user_id) REFERENCES user(id)
);

我有一个线程 table,其中包含第一个 post(作者的 post)的 ID。

如果我想在现有线程中插入新的 post,这很容易,因为我知道 thread_id.

但是如果我想创建一个新线程,我需要知道 post 的 post_id 还不存在。

目前我使用多个 SQL 查询和多个提交来完成它:

cur = db.execute("""
      INSERT INTO post (content, user_id)
      VALUES(?, ?, ?)""", [content, user_id])
db.commit()
post_id = cur.lastrowid
cur = db.execute("""
      INSERT INTO thread (title, post_id)
      VALUES(?, ?, ?)""", [title, post_id])
db.commit()
thread_id = cur.lastrowid
db.execute("""
      UPDATE post
      SET thread_id = ?
      WHERE id=?""", [thread_id, post_id])
db.commit()

但这很丑陋,我认为有更好的解决方案。 如果我能做这样的事情就完美了,但这是不允许的:

INSERT INTO thread(title)
    VALUES("thread 1");
INSERT INTO post(post, thread_id)
    VALUES("first post of thread 1", LAST_INSERT_ROWID() AS tmp);
UPDATE thread
    SET post_id = LAST_INSERT_ROWID()
    WHERE id = tmp;

有什么想法吗?

谢谢!

您不需要(也不应该)在语句之间调用 commit()

读取lastrowid是获取插入行的自增ID的正确方法。


不需要存储第一个 post 的 ID,因为它可以从其他信息中导出:

SELECT id FROM post WHERE thread_id = ? ORDER BY /* timestamp */ id LIMIT 1;

存储它仅作为优化才有意义,但您的问题中没有任何内容表明这是必要的。