我使用的是PHP和MySQL。
目标:
在具有自动递增id列的表中插入新行
在插入这一新行时,我想将插入的新行的自动递增id#复制到同一行/条目中的另一列中
创建时,新条目/行应具有自动递增的id列和另一个具有相同编号的列。
我最关心的问题:
我需要所有这些都正确可靠地发生,即使来自其他连接的其他事务可能在服务器上发生。
到目前为止
我对last_insert_id()知之甚少。。。我害怕能够可靠地使用它来满足我的需求
我是否会遇到这样的情况:自动递增的id#已经递增(可能是由于来自另一个连接的其他插入查询),而现在我将无法获得正确的id#?(当last_insert_id()在每个连接的基础上提供给客户端时,我并不完全理解这意味着什么)
last_insert_id()对事务处理得好吗?因为当事务回滚时,它们变得未定义?(如果回滚了另一个事务,然后我立即运行此脚本,那么我的脚本会为last_insert_id()返回NULL吗?)
我不理解mysql_insert_id();如何使用它,以及它是否会帮助我。
到目前为止,我一直在思考:
- 将
column
设置为last_INSERT_id()的INSERT行 - INSERT行;使用SELECT last_insert_id()更新
column
- 选择last_insert_id();将
auto-increment column
和column
设置为last_INSERT_id()+1的INSERT行
当我将选定的值插入到自动递增列中时会发生什么?自动递增生成器会从我插入的数字开始计数吗?如果我使用了一个以前使用过的值(但现在不存在了),并且在该值之后存在id为#的记录,该怎么办?
表或行锁定是否允许我实现所需的行为?
做这样的事情的正确方法是什么?
"last_insert_id()是在每个连接的基础上提供给客户端的"
last_insert_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方法。
请在我可能出错的地方为我更正我的输出。
您应该看看这篇关于MySQL last_insert_id
的文章
last_insert_id
是独立于客户端的,并且将从该客户端返回最后插入的行的ID,因此您不需要担心另一个连接上的用户与数据库进行交易的情况。
考虑到您可能对数据库、有多重访问权限
我会做:
1,只需插入新行并将null
放入"另一列"中,我们称之为[autoID_Copy]
2,然后我可以运行这个:
update table set autoID_Copy= autoID where autoID_Copy is null
甚至可以让它更快CCD_ 9或其它滤波器。
希望这能有所帮助。