mysql事务 - 混合插入&选择获得last_insert_id?

时间:2011-09-15 18:38:15

标签: php mysql database transactions pdo

我正在执行一个事务(使用PDO),但是我需要获取事务中第一个元素的插入ID,例如:

BEGIN
INSERT INTO user (field1,field2) values (value1,value2)
INSERT INTO user_option (user_id,field2) values (LAST_INSERT_ID(),value2);
COMMIT;

然后做pdo的东西:

[...]
$pdo->execute();
$foo = $pdo->lastInsertId(); // This needs to be the id from the FIRST insert

有没有办法从事务中的第一个元素获取最后一个插入ID?也许使用以下内容:

BEGIN
INSERT INTO user (field1,field2) values (value1,value2)
SELECT id AS user_id FROM user WHERE id=LAST_INSERT_ID()
INSERT INTO user_option (user_id,field2) values (LAST_INSERT_ID(),value2);
COMMIT;

$pdo->execute();
$fooArray = $pdo->fetchAll();
$lastId = $fooArray[0]['user_id'];

我是否完全与^共进午餐?有更好的方法吗?

编辑1

根据建议,我已更新查询以使用变量...但是,我不知道如何使用PDO检索变量值。使用$ stmt-> fetchAll()只返回一个空数组;

BEGIN
DECLARE User_ID int
DECLARE Option_ID int
INSERT INTO user (field1,field2) values (value1,value2);
set User_ID = select LAST_INSERT_ID();
INSERT INTO user_option (user_id,field2) values (LAST_INSERT_ID(),value2);
set Option_ID = select LAST_INSERT_ID();
select User_ID, Option_ID
COMMIT;

1 个答案:

答案 0 :(得分:2)

您可以这样做,将值放入变量然后选择它

BEGIN
DECLARE User_ID int
DECLARE Option_ID int
INSERT INTO user (field1,field2) values (value1,value2);
set User_ID = select LAST_INSERT_ID();
INSERT INTO user_option (user_id,field2) values (LAST_INSERT_ID(),value2);
set Option_ID = select LAST_INSERT_ID();
select User_ID, Option_ID
COMMIT;