dongshipang8094 2010-11-10 04:41
浏览 7
已采纳

多个插入查询

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

  • 写回答

3条回答 默认 最新

  • douge3830 2010-11-10 04:50
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?