假设我要在MySQL/InnoDB中模拟自动递增。
条件:
1. 使用MySQL/InnoDB 2. ID字段没有唯一索引,也不是主键
是否可能仅使用程序逻辑来模拟,而无需表级锁定?
谢谢。
条件:
1. 使用MySQL/InnoDB 2. ID字段没有唯一索引,也不是主键
是否可能仅使用程序逻辑来模拟,而无需表级锁定?
谢谢。
drop table if exists users_seq;
create table users_seq
(
next_seq_id int unsigned not null default 0
)engine = innodb;
drop table if exists users;
create table users
(
user_id int unsigned not null primary key,
username varchar(32) not null
)engine = innodb;
insert into users_seq values (0);
delimiter #
create trigger users_before_ins_trig before insert on users
for each row
begin
declare id int unsigned default 0;
select next_seq_id + 1 into id from users_seq;
set new.user_id = id;
update users_seq set next_seq_id = id;
end#
delimiter ;
insert into users (username) values ('f00'),('bar'),('bish'),('bash'),('bosh');
select * from users;
select * from users_seq;
insert into users (username) values ('newbie');
select * from users;
select * from users_seq;
CREATE TABLE sequence (id INTEGER); -- possibbly add a name;
INSERT INTO sequence VALUES (1); -- starting value
SET AUTOCOMMIT=0;
START TRANSACTION;
UPDATE sequence SET id = LAST_INSERT_ID(id+1);
INSERT INTO actualtable (non_autoincrementing_key) VALUES (LAST_INSERT_ID());
COMMIT;
SELECT LAST_INSERT_ID();
是一个安全的会话值,用来检查你得到的ID。确保你的表支持事务,或者序列中的空洞不是问题。
序列表需要将id设置为自增主键
users
(user_id
int(10) UNSIGNED NOT NULL DEFAULT 0,username
varchar(32) NOT NULL, PRIMARY KEY (user_id
) ) ENGINE=InnoDB; - David