2013-12-20 46 views
6

通过ONE查询在MySQL中多次插入后是否可以获得所有插入的ID? 例(摘要):获取MySQL中的最后一个插入的IDS

$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); 

它可以这样做,在这里(解决方案之一)。示例(摘要):

$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); 

但是,我想:一个查询INSERT的所有项目 - 一个查询获取所有插入的ID。

UPDATE

我的解决方案(基于问题generate an integer sequence in MySQL)由单一的查询最后插入ID`s的.Return序列。

$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)"; 

感谢您的关注!

+0

另请参阅http://stackoverflow.com/questions/16540997/get-all-inserted-ids-when-inserting-multiple-rows-using-a-single-query –

回答

2

MySQL的

SELECT LAST_INSERT_ID() 

将返回第一个ID从多线插入返回。 如果用

SELECT ROW_COUNT() 

结合起来,你可以通过在ROW_COUNT()指定的记录数与LAST_INSERT_ID()和增量开始。

相关问题