How do I get the ID of multiple inserted rows in MySQL?

后端 未结 3 1690
陌清茗
陌清茗 2020-11-27 19:59

I am inserting some words into a two-column table with this command:

INSERT IGNORE INTO terms (term) VALUES (\'word1\'), (\'word2\'), (\'word3\');

相关标签:
3条回答
  • 2020-11-27 20:33
    1. You get it via SELECT LAST_INSERT_ID(); or via having your framework/MySQL library (in whatever language) call mysql_insert_id().

    2. That won't work. There you have to query the IDs after inserting.

    0 讨论(0)
  • 2020-11-27 20:39

    First, to get the id just inserted, you can make something like :

    SELECT LAST_INSERT_ID() ;
    

    Care, this will work only after your last INSERT query and it will return the first ID only if you have a multiple insert!

    Then, with the IGNORE option, I don't think that it is possible to get the lines that were not inserted. When you make an INSERT IGNORE, you just tell MySQL to ignore the lines that would have to create a duplicate entry.

    If you don't put this option, the INSERT will be stopped and you will have the line concerned by the duplication.

    0 讨论(0)
  • 2020-11-27 20:48

    Why not just:

    SELECT ID
      FROM terms
     WHERE term IN ('word1', 'word2', 'word3')
    
    0 讨论(0)
提交回复
热议问题