mysql中插入一条记录返回该记录id

时间:2021-01-10 00:26:55

1.select max(id) from user;

2.select last_insert_id() as id from user limit 1; 
(这个测试的返回id一直是0,有点问题)

3.储存过程
1)
oracel中
create sequence seqID
minvalue 1
maxvalue 999999999999999999999999999
start with 1
increment by 1
nocache
order;

create or replace procedure sp_insert(aName int,rst out int) is
begin
  insert into tablename(id,name) values(seqID.nextval,aName);
  rst:=seqID.currval;
end;


2)mysql中实现
DELIMITER $$

DROP PROCEDURE IF EXISTS `test` $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `test`(in name varchar(100),out oid int)
BEGIN
  insert into user(loginname) values(name);
  select max(id) from user into oid;
  select oid;
END $$

DELIMITER ;

 

然后执行
call test('gg',@id);

就返回id