Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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".

like image 828
Googlebot Avatar asked Sep 21 '11 14:09

Googlebot


People also ask

How can I get insert id?

1. mysqli_insert_id() It returns the last AUTO_INCREMENT column value of the previous successfully executed insert query. It returns 0 when the table doesn't have any AUTO_INCREMENT column.

How do I get the unique ID for the last inserted row?

9 Obtaining the Unique ID for the Last Inserted Row. If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function.


2 Answers

  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.

like image 105
glglgl Avatar answered Oct 17 '22 03:10

glglgl


Why not just:

SELECT ID
  FROM terms
 WHERE term IN ('word1', 'word2', 'word3')
like image 1
mellamokb Avatar answered Oct 17 '22 03:10

mellamokb