[英]LAST_INSERT_ID() MySQL
I have a MySQL question that I think must be quite easy.我有一个 MySQL 问题,我认为这一定很容易。 I need to return the LAST INSERTED ID from table1 when I run the following MySql query:当我运行以下 MySql 查询时,我需要从 table1 返回 LAST INSERTED ID:
INSERT INTO table1 (title,userid) VALUES ('test',1);
INSERT INTO table2 (parentid,otherid,userid) VALUES (LAST_INSERT_ID(),4,1);
SELECT LAST_INSERT_ID();
As you can understand the current code will just return the LAST INSERT ID of table2 instead of table1, how can I get the id from table1 even if I insert into table2 between?正如您所理解的,当前代码只会返回 table2 的 LAST INSERT ID 而不是 table1,即使我在 table2 之间插入,我如何才能从 table1 获取 id?
You could store the last insert id in a variable :您可以将最后一个插入 ID 存储在一个变量中:
INSERT INTO table1 (title,userid) VALUES ('test', 1);
SET @last_id_in_table1 = LAST_INSERT_ID();
INSERT INTO table2 (parentid,otherid,userid) VALUES (@last_id_in_table1, 4, 1);
Or get the max id frm table1或者从 table1 获取最大 id
INSERT INTO table1 (title,userid) VALUES ('test', 1);
INSERT INTO table2 (parentid,otherid,userid) VALUES (LAST_INSERT_ID(), 4, 1);
SELECT MAX(id) FROM table1;
Since you actually stored the previous LAST_INSERT_ID() into the second table, you can get it from there:由于您实际上将先前的 LAST_INSERT_ID() 存储到第二个表中,因此您可以从那里获取它:
INSERT INTO table1 (title,userid) VALUES ('test',1);
INSERT INTO table2 (parentid,otherid,userid) VALUES (LAST_INSERT_ID(),4,1);
SELECT parentid FROM table2 WHERE id = LAST_INSERT_ID();
This enables you to insert a row into 2 different tables and creates a reference to both tables too.这使您可以在 2 个不同的表中插入一行并创建对两个表的引用。
START TRANSACTION;
INSERT INTO accounttable(account_username)
VALUES('AnAccountName');
INSERT INTO profiletable(profile_account_id)
VALUES ((SELECT account_id FROM accounttable WHERE account_username='AnAccountName'));
SET @profile_id = LAST_INSERT_ID();
UPDATE accounttable SET `account_profile_id` = @profile_id;
COMMIT;
I had the same problem in bash and i'm doing something like this:我在 bash 中遇到了同样的问题,我正在做这样的事情:
mysql -D "dbname" -e "insert into table1 (myvalue) values ('${foo}');"
which works fine:-) But效果很好:-) 但是
mysql -D "dbname" -e "insert into table1 (myvalue) values ('${foo}');set @last_insert_id = LAST_INSERT_ID();"
mysql -D "dbname" -e "insert into table2 (id_tab1) values (@last_insert_id);"
don't work.不工作。 Because after the first command, the shell will be logged out from mysql and logged in again for the second command, and then the variable @last_insert_id isn't set anymore.因为在第一个命令之后,shell 将从 mysql 中注销并重新登录第二个命令,然后变量@last_insert_id 不再设置。 My solution is:我的解决办法是:
lastinsertid=$(mysql -B -N -D "dbname" -e "insert into table1 (myvalue) values ('${foo}');select LAST_INSERT_ID();")
mysql -D "dbname" -e "insert into table2 (id_tab1) values (${lastinsertid});"
Maybe someone is searching for a solution an bash :-)也许有人正在寻找解决方案 bash :-)
We only have one person entering records, so I execute the following query immediately following the insert:我们只有一个人输入记录,所以我在插入后立即执行以下查询:
$result = $conn->query("SELECT * FROM corex ORDER BY id DESC LIMIT 1");
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
}
This retrieves the last id from the database.这将从数据库中检索最后一个 id。
It would be possible to save the last_id_in_table1 variable into a php variable to use it later?是否可以将 last_id_in_table1 变量保存到 php 变量中以便以后使用?
With this last_id I need to attach some records in another table with this last_id, so I need:有了这个last_id,我需要用这个last_id在另一个表中附加一些记录,所以我需要:
1) Do an INSERT and get the last_id_in_table1 1) 执行 INSERT 并获取 last_id_in_table1
INSERT into Table1(name) values ("AAA");
SET @last_id_in_table1 = LAST_INSERT_ID();
2) For any indeterminated rows in another table, UPDATING these rows with the last_id_insert generated in the insert. 2) 对于另一个表中的任何不确定行,使用插入中生成的 last_id_insert 更新这些行。
$element = array(some ids)
foreach ($element as $e){
UPDATE Table2 SET column1 = @last_id_in_table1 WHERE id = $e
}
For no InnoDB solution: you can use a procedure don't forgot to set the delimiter for storing the procedure with ;
对于没有 InnoDB 的解决方案:您可以使用过程don't forgot to set the delimiter for storing the procedure with ;
CREATE PROCEDURE myproc(OUT id INT, IN otherid INT, IN title VARCHAR(255))
BEGIN
LOCK TABLES `table1` WRITE;
INSERT INTO `table1` ( `title` ) VALUES ( @title );
SET @id = LAST_INSERT_ID();
UNLOCK TABLES;
INSERT INTO `table2` ( `parentid`, `otherid`, `userid` ) VALUES (@id, @otherid, 1);
END
And you can use it...你可以使用它...
SET @myid;
CALL myproc( @myid, 1, "my title" );
SELECT @myid;
而不是这个LAST_INSERT_ID()
尝试使用这个
mysqli_insert_id(connection)
In trigger BEFORE_INSERT this working for me:在触发器 BEFORE_INSERT 这对我有用:
SET @Last_Insrt_Id = (SELECT(AUTO_INCREMENT /*-1*/) /*as Last_Insert_Id*/
FROM information_schema.tables
WHERE table_name = 'tblTableName' AND table_schema = 'schSchemaName');
Or in simple select:或者在简单的选择中:
SELECT(AUTO_INCREMENT /*-1*/) as Last_Insert_Id
FROM information_schema.tables
WHERE table_name = 'tblTableName' AND table_schema = 'schSchemaName');
If you want, remove the comment /*-1*/
and test in other cases.如果需要,请删除注释/*-1*/
并在其他情况下进行测试。 For multiple use, I can write a function.对于多次使用,我可以编写一个函数。 It's easy.这很容易。
We could also use $conn->insert_id;我们也可以使用 $conn->insert_id; // Create connection // 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
最后和倒数第二:
INSERT INTO `t_parent_user`(`u_id`, `p_id`) VALUES ((SELECT MAX(u_id-1) FROM user) ,(SELECT MAX(u_id) FROM user ) );
My code does not work for me.我的代码对我不起作用。 Any idea to recover the id of my last insert this is my code I am new developing and I do not know much恢复我上次插入的 id 的任何想法这是我正在开发的代码,我不太了解
I GOT ERROR IN THE QUERY AND I DON'T KNOW HOW TO SEND PRINT IN THE LINE OF $ session-> msg ('s', "Product added successfully. Make cost configuration". LAST_INSERT_ID ());我在查询中遇到错误,我不知道如何在 $ session-> msg ('s', "产品添加成功。进行成本配置".LAST_INSERT_ID ()) 行中发送打印
ALREADY VERIFY AND IT IS CORRECT THE CONNECTION AND THE FIELDS OF THE DATABASE.已经验证并且数据库的连接和字段是正确的。
<?php
if(isset($_POST['add_producto'])){
$req_fields = array( 'nombre', 'categoria', 'proveedor');
validate_fields($req_fields);
if(empty($errors)){
$codigobarras = remove_junk($db->escape($_POST['codigobarras']));
$identificador = remove_junk($db->escape($_POST['identificador']));
$nombre = remove_junk($db->escape($_POST['nombre']));
$categoria = (int)$db->escape($_POST['categoria']);
$etiquetas = remove_junk($db->escape($_POST['etiquetas']));
$unidadmedida = remove_junk($db->escape($_POST['unidadmedida']));
$proveedor = remove_junk($db->escape($_POST['proveedor']));
$fabricante = remove_junk($db->escape($_POST['idfabricante']));
$maximo = remove_junk($db->escape($_POST['maximo']));
$minimo = remove_junk($db->escape($_POST['minimo']));
$descripcion = remove_junk($db->escape($_POST['descripcion']));
$dias_vencimiento = remove_junk($db->escape($_POST['dias_vencimiento']));
$servicio = "0";
if (isset($_POST['servicio'])){
$servicio =implode($_POST['servicio']);
}
$numeroserie = "0";
if (isset($_POST['numeroserie'])){
$numeroserie =implode($_POST['numeroserie']);
}
$ingrediente = "0";
if (isset($_POST['ingrediente'])){
$ingrediente =implode($_POST['ingrediente']);
}
$date = make_date();
$query = "INSERT INTO productos (";
$query .=" codigo_barras,identificador_producto,nombre,idcategoria,idetiquetas,unidad_medida,idproveedor,idfabricante,max_productos,min_productos,descripcion,dias_vencimiento,servicio,numero_serie,ingrediente,activo";
$query .=") VALUES (";
$query .=" '{$codigobarras}', '{$identificador}', '{$nombre}', '{$categoria}', '{$etiquetas}', '{$unidadmedida}', '{$proveedor}', '{$fabricante}', '{$maximo}', '{$minimo}', '{$descripcion}', '{$dias_vencimiento}', '{$servicio}', '{$numeroserie}', '{$ingrediente}', '1'";
$query .=");";
$query .="SELECT LAST_INSERT_ID();";
if($db->query($query)){
$session->msg('s',"Producto agregado exitosamente. Realizar configuracion de costos" . LAST_INSERT_ID());
redirect('precio_producto.php', false);
} else {
$session->msg('d',' Lo siento, registro falló.');
redirect('informacion_producto.php', false);
}
} else{
$session->msg("d", $errors);
redirect('informacion_producto.php',false);
}
}
?>
Just to add for Rodrigo post, instead of LAST_INSERT_ID() in query you can use SELECT MAX(id) FROM table1;, but you must use (),只是为了添加 Rodrigo 帖子,而不是 LAST_INSERT_ID() 在查询中你可以使用 SELECT MAX(id) FROM table1;,但你必须使用 (),
INSERT INTO table1 (title,userid) VALUES ('test', 1)
INSERT INTO table2 (parentid,otherid,userid) VALUES ( (SELECT MAX(id) FROM table1), 4, 1)
如果您需要从 mysql 获得,在您的查询之后,没有另一个查询的最后一个自动增量 id,请输入您的代码:
mysql_insert_id();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.