SQL插入行和复制插入的自动增量ID到另一列

时间:2015-02-12 18:33:36

标签: php mysql auto-increment sql-insert last-insert-id

我正在使用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. 的INSERT行
  3. INSERT行;使用SELECT last_insert_id();
  4. 更新column
  5. SELECT last_insert_id(); INSERT行auto-increment columncolumn设置为last_insert_id()+ 1
  6. 将所选值插入自动增量列时会发生什么?自动增量发生器是否会从插入的数字开始计数?如果我使用之前已经使用过的值(但不再存在)并且存在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方法。


    如果我错了,请纠正我的输出。

2 个答案:

答案 0 :(得分:0)

您应该查看有关MySQL last_insert_id

this article

last_insert_id与客户端无关,将返回该客户端最后插入行的ID,因此您无需担心另一个连接上的用户与数据库进行交易。

答案 1 :(得分:-1)

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

我会这样做:

1,只需插入新行并将null放入“另一列”即可称之为[autoID_Copy]

2,然后我可以运行:

update table set autoID_Copy= autoID where autoID_Copy is null 

甚至可以让你做得更快  where timeInstered < 1 min或者其他一些过滤器。

希望这有帮助。

相关问题