简体   繁体   English

锁定MySQL中的最大值

[英]Lock the maximum value in MySQL

I am using the following query on MySQL using PHP我使用 PHP 在 MySQL 上使用以下查询

$sql = SELECT MAX(SrNo) FROM cart;
$result = mysql_query($sql);

The structure of table CART is表 CART 的结构是

CART (SrNo int(10));

Now I am using the result to do some kind of processing and inserting the maximum value into this table by incrementing one.现在我正在使用结果进行某种处理,并通过递增一个将最大值插入到该表中。 My problem is that if user1 has got the maximum value of SrNo and is in-between the processing.我的问题是,如果 user1 获得了SrNo的最大值并且在处理之间。 During this time user2 also requests the server got the same maximum value of SrNo as user1 got and starts processing.在此期间,user2 还请求服务器获得与 user1 获得的相同的 SrNo 最大值并开始处理。

Now when both are done with the processing + insertion into the table, I will have two duplicates in the table CART.现在,当两者都完成了处理+插入到表中时,我将在表 CART 中有两个重复项。 How can I prevent this from happening?我怎样才能防止这种情况发生?

In other words, I want no one else to get the maximum value of SrNo until unless one user is finished doing its processing.换句话说,我不希望其他人获得SrNo的最大值,直到一个用户完成其处理。

NOt a trivial thing with a web application that creates a new connection on each request.对于在每个请求上创建新连接的 web 应用程序来说,这不是一件小事。 You'd need to add a lockedBy and lockedTime columns to this table, and put into them an ID of user that requested the lock as well as timestamp of when the lock was requested.您需要在该表中添加lockedBylockedTime列,并在其中放入请求锁的用户ID以及请求锁的时间戳。 You need the timestamp, so that you can ignore locks that are longer than certain amount of time.您需要时间戳,以便您可以忽略超过一定时间的锁。

if you set SrNo as the primary key on the table, then the secound time you try to add the row going to fail, and if it fails, you can request a new number.如果将 SrNo 设置为表上的主键,则第二次尝试添加行将失败,如果失败,则可以请求新编号。

ALTER TABLE cart ADD PRIMARY KEY (SrNo);

wouldn't you be fine with the AUTO_INCREMENT feature for PRIMARY KEY?对 PRIMARY KEY 的 AUTO_INCREMENT 功能你不满意吗?

create table cart ( SrNo int(10) AUTO_INCREMENT PRIMARY KEY ) ENGINE = InnoDB;

then just simply insert new lines and it will automatically increment the new values.然后只需简单地插入新行,它就会自动增加新值。 That would probably very easily do the trick you are (maybe?) trying to do.这可能很容易做到你(也许?)试图做的伎俩。

But if you need to lock the maxmium, you can do this:但是如果你需要锁定最大值,你可以这样做:

start transaction;
select max(SrNo) from cart for update;
/* do some other stuff, insert the max value + 1 etc... */
commit;

Remember: You should use transaction for any operation which is not 1 single query!请记住:您应该将事务用于不是 1 个单一查询的任何操作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM