mysql 模拟sequence,在MySQL中模拟事务安全的SEQUENCE

We're using MySQL with InnoDB storage engine and transactions a lot, and we've run into a problem: we need a nice way to emulate Oracle's SEQUENCEs in MySQL. The requirements are:

- concurrency support

- transaction safety

- max performance (meaning minimizing locks and deadlocks)

We don't care if some of the values won't be used, i.e. gaps in sequence are ok. There is an easy way to archieve that by creating a separate InnoDB table with a counter, however this means it will take part in transaction and will introduce locks and waiting. I am thinking to try a MyISAM table with manual locks, any other ideas or best practices?

解决方案

If auto-increment isn't good enough for your needs, you can create a atomic sequence mechanism with n named sequences like this:

Create a table to store your sequences:

CREATE TABLE sequence (

seq_name varchar(20) unique not null,

seq_current unsigned int not null

);

Assuming you have a row for 'foo' in the table you can atomically get the next sequence id like this:

UPDATE sequence SET seq_current = (@next := seq_current + 1) WHERE seq_name = 'foo';

SELECT @next;

No locks required. Both statements need to be executed in the same session, so that the local variable @next is actually defined when the select happens.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值