Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last inserted IDS in MySQL [duplicate]

Tags:

php

mysql

Is it possible to get ALL inserted ID`s after multiple insert in MySQL by ONE query? Example(abstract):

$ids = array();
$parts = array();
$query = 'INSERT INTO `TABLENAME` (`FIELDS`)  VALUES'; 

$items = array(values);
foreach($items as $item){
   $parts[] = '('.$item['key1'].','.$item['key2']...','.$item['keyN'].')';
}

$query .= implode(',',$parts);
mysqli_query($link,$query);
$ids = ... // getting  ALL inserted IDs
var_dump($ids);

It can do so here (one of solutions). Example(abstract):

$ids = array();

$items = array(values);
foreach($items as $item){
   $query ='INSERT INTO `TABLENAME` (`FIELDS`)  VALUES('.$item['key1'].','.$item['key2']...','.$item['keyN'].')';
   mysqli_query($link,$query);
   $ids[] = mysqli_insert_id($link);
}
var_dump($ids);  

But, I would like to : one query INSERT all items - one query get ALL inserted ids.

UPDATE

My solution ( based on question generate an integer sequence in MySQL ).Return sequence of last inserted ID`s by single query.

$query_inserted_ids = "SELECT @row := @row +1 AS row_id
                       FROM TABLENAME , (SELECT @row := LAST_INSERT_ID()-1 )r
                       WHERE @row <(
                       SELECT id
                       FROM  TABLENAME 
                       ORDER BY id DESC
                       LIMIT 1 )";

Thanks for attention!

like image 941
voodoo417 Avatar asked Dec 20 '13 14:12

voodoo417


1 Answers

MySQL's

SELECT LAST_INSERT_ID()

Will return the FIRST ID returned from a multi-line insert. If you combine it with

SELECT ROW_COUNT()

you can start with the LAST_INSERT_ID() and increment by the number of records specified in ROW_COUNT().

like image 142
Digital Chris Avatar answered Sep 30 '22 20:09

Digital Chris