gpt4 book ai didi

php - 增量计数器mysql

转载 作者:行者123 更新时间:2023-11-29 04:10:45 25 4
gpt4 key购买 nike

我的问题很简单,但回答起来可能很棘手。

我在使用 PHP,我想手动管理我的对象的唯一 ID。棘手的是管理原子性。我不希望 2 个元素获得相同的 ID。

“元素”被分组在“组”中。在每个组中,我希望元素 ID 从 1 开始,并针对该组中的每个插入递增增长。

我的第一个解决方案是在“Groups”表中添加一个“lastID”列:

CREATE TABLE groups ( id INT AUTO_INCREMENT, lastId INT )
CREATE TABLE elements ( myId INT, multiple values ...)

为了避免许多元素具有相同的 ID,我必须更新 lastId 并在原子 SQL 查询中选择它。

在那之后,一个检索,我有一个唯一的 ID,不能再次选择,我可以插入我的元素。

我的问题是如何解决粗体部分?我的数据库是带有 MyISAM 引擎的 MySQL,因此没有事务支持。

UPDATE groups 
SET lastId = lastId + 1
WHERE id = 42

SELECT lastId
FROM groups
WHERE id = 42

还有比这 2 个请求更原子化的东西吗?

谢谢

最佳答案

UPDATE groups SET lastId = last_insert_id(lastId + 1)

然后你就可以得到你的新ID

SELECT last_insert_id()

last_insert_id 与参数一起使用将存储值并在稍后调用时返回它。
这种生成自动编号的方法最适用于只有几行的 MyISAM 表(MyISAM 总是锁定整个表)。它还具有在事务期间不锁定表的好处(如果它是 InnoDB 表,则会发生这种情况)。

这是来自 MySQL manual :

If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID(). This can be used to simulate sequences:

Create a table to hold the sequence counter and initialize it:

CREATE TABLE sequence (id INT NOT NULL); 
INSERT INTO sequence VALUES (0);

Use the table to generate sequence numbers like this:

UPDATE sequence SET id=LAST_INSERT_ID(id+1);
SELECT LAST_INSERT_ID();

The UPDATE statement increments the sequence counter and causes the next call to LAST_INSERT_ID() to return the updated value. The SELECT statement retrieves that value. The mysql_insert_id() C API function can also be used to get the value. See Section 21.8.3.37, “mysql_insert_id()”.

You can generate sequences without calling LAST_INSERT_ID(), but the utility of using the function this way is that the ID value is maintained in the server as the last automatically generated value. It is multi-user safe because multiple clients can issue the UPDATE statement and get their own sequence value with the SELECT statement (or mysql_insert_id()), without affecting or being affected by other clients that generate their own sequence values.

关于php - 增量计数器mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11639234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com