开发者

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

开发者 https://www.devze.com 2023-04-06 05:34 出处:网络
I am inserting some words into a two-column table with this command: INSERT IGNORE INTO terms (term) VALUES (\'word1\'), (\'word2\'), (\'word3\');

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

INSERT IGNORE INTO terms (term) VALUES ('word1'), ('word2'), ('word3');
  1. How can I get the ID (Primary Key) of the row in which each word is inserted. I mean returning a value like "55,56,57" after executing INSERT. Does MySQL have such a response?

  2. The term column is UNIQUE. If a term already exists, MySQL 开发者_开发知识库will not insert it. Is it possible to return the reference for this duplication (i.e. the ID of the row in which the term exists)? A response like "55,12,56".


  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.


Why not just:

SELECT ID
  FROM terms
 WHERE term IN ('word1', 'word2', 'word3')


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

精彩评论

暂无评论...
验证码 换一张
取 消