问题描述
在给定的表中,我必须填写:pos(销售点)和凭证_编号。
它们都分组在一个唯一索引中
例如,我需要每个 pos 有一个唯一的序列
ID | 日期 | 位置 | voucher_number |
---|---|---|---|
1 | 2021-01-01 11:45:37 | 1 | 1 |
2 | 2021-01-01 17:22:45 | 1 | 2 |
3 | 2021-01-02 15:08:02 | 2 | 1 |
4 | 2021-01-02 15:08:02 | 1 | 3 |
5 | 2021-01-03 10:37:24 | 2 | 2 |
6 | 2021-01-03 10:37:24 | 3 | 1 |
7 | 2021-01-03 10:37:24 | 1 | 4 |
不同的用户可以同时创建不同的凭证,所以我关心的是如何确保顺序保持自然顺序,不重复或跳过数字
我正在处理的代码包含在一个事务中,我正在考虑做这样的事情(伪):
//At this point a transaction has already been started
function save_voucher($voucher_data)
{
//Notice the SELECT ... FOR UPDATE
$max_voucher_number = select max(voucher_number) as max_voucher_number from vouchers where pos = $voucher_data["pos"] for update;
$voucher_data["voucher_number"] = $max_voucher_number + 1;
//I can't alter save_voucher() in parent class
//But inside it would perform something like:
//insert into (pos,voucher_number) values ($voucher_data["pos"],$voucher_data["voucher_number"]);
return parent::save_voucher($voucher_data);
}
//After the method execution,a commit or rollback happens;
甚至类似:
//At this point a transaction has already been started
function save_voucher()
{
//I can't alter save_voucher() in parent class
$new_voucher_id = parent::save_voucher();
//Now,after a voucher had been created I could get the max sequence
//Notice the SELECT ... FOR UPDATE
$max_voucher_number = select max(voucher_number) as max_voucher_number from vouchers where pos = $pos for update;
//Then,I could update that voucher
update vouchers set voucher_number = $max_voucher_number + 1 where id = $new_voucher_id;
return $new_voucher_id;
}
//After the method execution,a commit or rollback happens;
以上是否可以保证每个 pos 都有唯一的序列?可能的并发是否会以任何方式影响序列?
我将 MySQL 与所有使用 InnoDB 的表一起使用
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)