多个插入查询

发布于 2024-10-02 03:40:12 字数 266 浏览 1 评论 0原文

我有三个基本上向下级联的表,例如:

  • 主题
  • 部分(引用主题 id)
  • 子部分(引用主题 id 和部分 id)

编写 mysql 语句来创建初始主题/部分/子部分的最佳方法是什么,以便我可以获取 id (auto_incremented) 新创建的行并使用它们将它们插入到后两行中?

编辑 我正在使用 phpbb3,不知道这是否有很大的不同,但我通常使用 $db-sql_query() 函数

I have three tables that essentially cascade down, like:

  • topic
  • section (references topic id)
  • subsection (references topic id and section id)

Whats the best method of writing mysql statements to create the initial topic/section/subsection so I can grab the id's (auto_incremented) of the newly created rows and use them to insert them into the second two?

edit
I'm using phpbb3, dunno if that makes a huge difference, but I normally use the $db-sql_query() function

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

何必那么矫情 2024-10-09 03:40:12

从父母那里,一直到下线。
然后您可以使用 LAST_INSERT_ID(),或在 SELECT 中插入:

INSERT INTO TOPIC
  (topic_id, topic)
VALUES (DEFAULT, $topic);

INSERT INTO SECTION
  (topic_id, section)
SELECT topic_id, $section
  FROM TOPIC
 WHERE topic = $topic

INSERT INTO SUBSECTION
  (section_id, topic_id, subsection)
SELECT section_id, topic_id
  FROM SECTION 
 WHERE section = $section

此示例假设 TOPIC.topic_idSECTION.section_idSUBSECTION 是 auto_increment 主键列。

From the parent, down the line.
Then you can use either LAST_INSERT_ID(), or INSERT in the SELECT:

INSERT INTO TOPIC
  (topic_id, topic)
VALUES (DEFAULT, $topic);

INSERT INTO SECTION
  (topic_id, section)
SELECT topic_id, $section
  FROM TOPIC
 WHERE topic = $topic

INSERT INTO SUBSECTION
  (section_id, topic_id, subsection)
SELECT section_id, topic_id
  FROM SECTION 
 WHERE section = $section

This example assumes that TOPIC.topic_id, SECTION.section_id, and SUBSECTION are auto_increment, primary key columns.

溺孤伤于心 2024-10-09 03:40:12

您可以使用 mysql_insert_id() 来获取最后一个插入 ID。有关更多详细信息,请参阅参考

You can use mysql_insert_id() to get the last insert ID. see reference for more details.

萌逼全场 2024-10-09 03:40:12

据我了解,只有一种方法,那就是自上而下。
要将小节添加到节中,您必须已经插入了节。
要将主题添加到小节,请确保先添加该小节。
在此过程中,您会跟踪最后插入的 ID(如果您刚刚创建它),以便将其提供给下一个实体。

As far as I understand, there's only one way, which is top-down.
To add a subsection to a section, you must have had a section already inserted.
To add a topic to a subsection, make sure you added the subsection first.
On the way, you keep track of the last inserted ID (if you just created it) to give it to the next entity down the line.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文