doulou1970 2009-10-16 08:33
浏览 62
已采纳

保留MySQL事务中的自动增量ID

I have two MySQL database tables that are meant to hold data for eshop orders. They're built as such (extremely simplified version):

CREATE TABLE `orders` (
`id` int(11) NOT NULL auto_increment
PRIMARY KEY  (`id`)
);

CREATE TABLE `order_items` (
  `id` int(11) NOT NULL auto_increment,
  `orderID` int(11) NOT NULL,
  PRIMARY KEY  (`id`)
)

The relationship between the two is that orders.id corresponds to order_items.orderID.

I'm using a transaction to place a new order, however have a problem preserving the above relationship. In order to get the new order id. I have to commit the orders INSERT query, get the autoincremented id and then start another transaction for the order items. Which pretty much defeats the point of using transactions.

I could insert the new order in the orders table and then try something like

INSERT INTO order_items(orderID) VALUES(LAST_INSERT_ID()) 

which I assume would work. However after the first order item is inserted LAST_INSERT_ID() would stop returning the order id and instead return the order item id making it impossible to use this query to insert another order item.

Is there a way to make this whole thing work within a single transaction or should I give up and use a procedure instead?

  • 写回答

2条回答 默认 最新

  • duanheye7909 2009-10-16 08:37
    关注

    WOuld this work?:

    INSER QUERY;
    SET @insertid = LAST_INSERT_ID();
    INSERT INTO `order_items` SET `OrderID` = @insertid;
    

    All in one statement. You will have to double check the syntax

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器