简体   繁体   English

在关系数据库中,如何从其他表中获取最后一个插入ID

[英]In a relational database, how do i get the last insert id from a different table

I have two tables that are relational, how do I get the last id of say the first table and use it in another table. 我有两个关系表,如何获得说第一个表的最后一个ID并在另一个表中使用它。 I want the $welfare_id variable get the last_insert_id of the first table (another table). 我希望$welfare_id变量获取第一个表(另一个表)的last_insert_id

Here is the code: 这是代码:

<?php
include_once('config.php');

if (isset($_POST['record'])) {
    $payeeName = $_POST['payeeName'];
    $amount = $_POST['amount'];
    $welfare_id = LAST_INSERT_ID();

    $myd = $pdo->prepare('INSERT INTO welfare_funeral_payees(Name, Amount, welfare_id)VALUES(:upayeeName, :uamount, :uwelfare_id)');
    $myd->bindParam(':upayeeName', $payeeName);
    $myd->bindParam(':uamount', $amount);
    $myd->bindParam(':uwelfare_id', $welfare_id);


    if ($myd->execute()) {
        ?>
        <script>
            alert("New Welfare created");
        </script>
        <?php
    } else {
        ?>
        <script>
            alert("Couln't not create Welfare");
        </script>
        <?php
    }
}
?>

you have to consider that LAST_INSERT_ID() work on a per-connection base, so, as stated in mysql manual: 您必须考虑LAST_INSERT_ID()在每个连接的基础上工作,因此,如mysql手册中所述:

The ID that was generated is maintained in the server on a per-connection basis. 生成的ID在每个连接的服务器中维护。 This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. 这意味着函数返回给定客户端的值是针对该客户端影响AUTO_INCREMENT列的最新语句生成的第一个AUTO_INCREMENT值。 This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. 即使其他客户端生成自己的AUTO_INCREMENT值,该值也不会受到其他客户端的影响。 This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions. 此行为可确保每个客户端都可以检索自己的ID,而不必担心其他客户端的活动,也不需要锁或事务。

this means that you can meaningfully call LAST_INSERT_ID() only after an insert and that id is relevant only for that particular client. 这意味着您只能在插入后才有意义地调用LAST_INSERT_ID(),并且该ID仅与该特定客户端相关。

To solve your problem you have to ways: use MAX (as suggested by Nic3500), which has the problem that you are not sure of which id you are really using, or pass the id you need in your post, retrieving in some way before the post (for instance, from a list of already created "welfare") 要解决您的问题,您必须采取以下方式:使用MAX(如Nic3500所建议),该问题是您不确定自己真正使用的ID,还是在帖子中传递所需的ID,然后才能以某种方式检索帖子(例如,从已经创建的“福利”列表中)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM