如何获取第一个查询的ID并将其用于第三个查询?

时间:2015-02-16 05:41:54

标签: mysql sql

我有关于SQL Query的问题。我的代码中有3个Insert个查询。 第一个查询是自动增量ID。

INSERT INTO master_tbl

第二个Insert将使用LAST_INSERT_ID()函数从第一个查询中获取ID。

INSERT INTO process (id_ref, process_id, hot_cold, temp) 
VALUES (LAST_INSERT_ID(), '4', '-', '12')

我的问题是,我有第三个查询需要将第一个查询中生成的ID用作id_ref

当我使用LAST_INSERT_ID()时,它获取的ID是第二个查询的ID。

有关如何在第3次查询中仍然使用ID的任何建议?

2 个答案:

答案 0 :(得分:0)

您可以声明变量并将第一个查询ID存储在该变量中,然后在任意位置使用它。

 After first query as you mentioned you are using the separate queries you can try using select to set the `Last insert id` into the variable and then use that variable as below,

   select @valuetoUse := LAST_INSERT_ID()

或者其他方式是使用select来获取代码中的值,然后将该值作为所有其他值传递。为了获得价值,您可以直接触发select

     SELECT LAST_INSERT_ID()

然后在第二个查询中

   INSERT INTO process (id_ref, process_id, hot_cold, temp) 
   VALUES (valuetoUse , '4', '-', '12')

然后再次在第三个查询中

   INSERT INTO thirdtable (id_ref, process_id, hot_cold, temp) 
   VALUES (valuetoUse , '4', '-', '12')

For more info on how to use user defined variables see here.

答案 1 :(得分:0)

功能与@Coder代码告诉的相同但是使用PHP

试试这个

创建连接

$conn = new mysqli($servername, $username, $password, $dbname);

首先插入表1

INSERT INTO master_tbl

然后做

$sql = "SELECT MAX(id) as id from master_tbl";
$result = $conn->query($sql);
$row = $result->fetch_array(MYSQLI_NUM);
$latest_id=$row[0];

$sql = "INSERT INTO process (id_ref, process_id, hot_cold, temp)
 VALUES ($latest_id,'4','-','12')";

if ($conn->query($sql) === TRUE) 
{
    echo "New record created successfully";
}

$sql = "INSERT INTO table3 (id_ref , columns list)
 VALUES ($latest_id,other fields)";

if ($conn->query($sql) === TRUE) 
{
    echo "New record created successfully";
}