获取最后2个自动增量ID

时间:2016-07-26 15:16:18

标签: php mysql

我设法获取最后一次插入查询的最后一个ID,但也没有获得第二个ID。我怎样才能做到这一点?我需要两者填充连接表

$query="INSERT INTO  $dbname.Product (Description, ***, **, **, **) VALUES ('$des','$**', '$**', '$**', '$**')";
        $result = mysqli_query($conn,$query);
        $id =  mysqli_insert_id($conn);
        $query2 = "INSERT INTO  $dbname.Classification (**, **, **) VALUES ('$**', '$**', '$***')";     

        $result2 = mysqli_query($conn,$query2); 
        $id2 =  mysqli_insert_id($conn);
        echo $id;
        echo $id2;   //print the same ID as $id2

1 个答案:

答案 0 :(得分:1)

如果您评估两个不同的用户在同一秒内没有创建两个产品的风险,您可以使用类似这样的查询。

INSERT INTO $dbname.myTable (id_product, id_classification) VALUES((SELECT id_product FROM $dbname.Product ORDER BY id_product DESC LIMIT 1), (SELECT id_classification FROM $dbname.Classification  ORDER BY id_classification DESC LIMIT 1));

如果很多人可以同时创建产品并且冲突的风险很高,那么我使用了存储过程并且我在每个变量之后将最后插入的id的值存储在变量中查询。

DELIMITER //

CREATE PROCEDURE createProduct(
[your paramters],
dbName AS VARCHAR(50)
) 
BEGIN

    DECLARE idProduct INT(10) UNSIGNED;
    DECLARE idClassification INT(10) UNSIGNED;

    DECLARE EXIT HANDLER FROM SQLEXCEPTION BEGIN
        ROLLBACK;
        RESIGNAL;
    END;

    START TRANSACTION;

    INSERT INTO  dbname.Product (Description, ***, **, **, **) VALUES ('$des','$**', '$**', '$**', '$**');

    SET idProduct = LAST_INSERTED_ID();

    INSERT INTO dbname.Classification (**, **, **) VALUES ('$**', '$**', '$***');

    SET idClassification = LAST_INSERTED_ID();

    INSERT INTO $dbname.myTable (id_product, id_classification) VALUES (idProduct, idClassification);

    COMMIT;

END//