1

我正在使用 PHP 和 MySQL。

目标:

将新行插入具有自动递增 id 列的表中。
在插入此新行时,我想将新插入行的自动增量 ID # 复制到同一行/条目中的另一列中。
创建后,新条目/行应具有自动递增的 id 列和具有相同编号的另一列。

我最大的担忧:
我需要所有这些都正确可靠地发生,即使来自其他连接的其他事务可能正在服务器上发生。

至今

我对 last_insert_id() 只知道一点点......而且我害怕能够可靠地使用它来满足我的需要......
我是否会遇到自动增量 id # 已经增加的情况(由于可能来自另一个连接的其他一些插入查询)现在我不会得到正确的 id #? (我并没有完全理解将 last_insert_id() 以每个连接为基础提供给客户端的含义)。

last_insert_id() 是否会很好地处理事务,因为当事务回滚时它们变得未定义?(如果回滚另一个事务,然后我立即运行此脚本,我的脚本是否会为 last_insert_id() 返回 NULL?)

我不明白 mysql_insert_id(); 如何使用它以及它是否对我有帮助。

到目前为止,我想过:

  1. 插入行,column设置为 last_insert_id();
  2. 插入行;使用 SELECT last_insert_id column() 更新;
  3. 选择 last_insert_id(); 插入行auto-increment columncolumn设置为 last_insert_id()+1

当我将选定的值插入自动增量列时会发生什么?自动增量生成器会从我插入的数字开始计数吗?如果我使用以前使用过的值(但不再存在)并且存在 ID # 在该值之后的记录怎么办?

表或行锁定是否允许我实现我想要的行为?

做这样的事情的正确/正确方法是什么?



“last_insert_id() 在每个连接的基础上提供给客户端”

last_insert_id 与客户端无关,将返回来自该客户端的最后插入行的 ID,因此您无需担心另一个连接上的用户与数据库进行事务处理的情况。

我还是没完全明白那是什么意思……

对于基本场景:

INSERT row where id = 1;
SELECT last_insert_id(); outputs 1

Person A makes a connection to the db; SELECT last_insert_id(); outputs 1.
Person B makes a connection to the db; SELECT last_insert_id(); outputs 1?

Person A INSERT another row where id = 2;

Person A SELECT last_insert_id(); outputs 2?
Person B SELECT last_insert_id(); outputs... 1 or 2??

这里会发生什么?


还有一个真正让我担心的场景:

Person A makes a connection with the db;
Person A SELECT last_insert_id(); outputs 1

Person A INSERT row where id = 2;
Person A SELECT last_insert_id(); outputs 2

Person B makes a connection with the db;
Person B SELECT last_insert_id(); outputs 2
Person B INSERT row where id = 3;

Person A SELECT last_insert_id(); outputs 2??
Person B SELECT last_insert_id(); outputs 3??

在这种情况下,人员 A 的 last_insert_id() 落后了一个计数。如果这是真的,那么我将无法使用我的#3 方法。


无论我可能错在哪里,请为我纠正我的输出。

4

2 回答 2

0

你应该看看这篇关于 MySQL的文章last_insert_id

last_insert_id独立于客户端,并且会从该客户端返回最后插入的行的 ID,因此您无需担心另一个连接上的用户与数据库进行事务处理的情况。

于 2015-02-12T22:55:36.767 回答
-1

考虑到您可能可以多次访问您的数据库,

我会做:

1,只需插入新行并放入null“另一列”让我们称之为[autoID_Copy]

2,然后我可以运行这个:

update table set autoID_Copy= autoID where autoID_Copy is null 

甚至让它更快,你可能会做 where timeInstered < 1 min或者可能是其他一些过滤器。

希望这有帮助。

于 2015-02-12T22:54:57.467 回答