29

如何获取最后插入的 id?

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_insertzonemsg`

   (IN User_Id INT(10),
    IN zid INT(10),
    IN update_titles VARCHAR(50),
    IN textarea1s TEXT,
    IN filupload1s TEXT,
    IN audio1s VARCHAR(100),
    OUT out_id INT(10))
        BEGIN
        INSERT INTO zone_message_master
        **(user_id,ZoneID,update_title,textarea1,filupload1,
        audio1,LastUpdate)**
        VALUE
        **(User_Id,zid,update_titles,textarea1s,
        filupload1s,audio1s,NOW());**

SELECT **id** as **out_id**
FROM **zone_message_master** LAST_INSERT_ID();
END$$

我需要以out_id表格形式返回最后插入的 IDzone_message_master吗?

4

2 回答 2

47

您需要使用 SET 语句。例如 -

桌子:

CREATE TABLE table1(
  id INT(11) PRIMARY KEY AUTO_INCREMENT,
  column1 VARCHAR(10),
  column2 VARCHAR(10)
);

程序主体:

BEGIN
  INSERT INTO table1(column1, column2) VALUES ('value1', 'value2');
  SET out_param = LAST_INSERT_ID();
END

请注意,该 ID 字段未在 INSERT 语句中指定。该值将自动插入;当然,这个 ID 字段必须有 AUTO_INCREMENT 选项。

于 2012-10-31T06:59:49.873 回答
15

您可以借助以下代码获取最后插入 ID:-

只需创建一个存储过程:

CREATE DEFINER=`root`@`localhost` PROCEDURE `add_enquiry`(
IN EnquiryNo varchar(40),
IN OpeningDate date,
IN ClosingDate date,
IN  CreatedOn date,
OUT LID int(11)
)

BEGIN

INSERT into `enquiries` SET `enquiry_no`=EnquiryNo ,`opening_date`=OpeningDate ,`closing_date`=ClosingDate,`created_on` =CreatedOn;

SET LID = LAST_INSERT_ID();
END    

调用 PHP:

$rs = $dbh->query('CALL add_enquiry("ENQ" ,"2016-08-19","2016-08-18", "2016-11-23",@LID)'); 

$rs2 = $dbh->query("SELECT @LID as id");
$row = $rs2->fetchObject();
echo $row->id;
于 2016-11-26T12:20:17.177 回答