简体   繁体   English

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

[英]Preserve Autoincrement ID Within MySQL Transaction

I have two MySQL database tables that are meant to hold data for eshop orders. 我有两个MySQL数据库表,用于保存eshop订单的数据。 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. 两者之间的关系是orders.id对应于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. 为了获得新的订单ID。 I have to commit the orders INSERT query, get the autoincremented id and then start another transaction for the order items. 我必须提交订单INSERT查询,获取自动递增的ID,然后为订单项目启动另一笔交易。 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. 但是,在插入第一个订单商品后, LAST_INSERT_ID()将停止返回订单ID,而是返回该订单商品ID,因此无法使用此查询插入另一个订单商品。

Is there a way to make this whole thing work within a single transaction or should I give up and use a procedure instead? 有没有办法使整个事情在单个事务中起作用,还是应该放弃并使用一个过程?

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 您将必须仔细检查语法

You can't count on LAST_INSERT_ID() because it also changes when you insert values to order_items because it inserts its id which is also auto_imcrement. 您不能指望LAST_INSERT_ID(),因为当您向order_items插入值时它也会更改,因为它会插入其id也是auto_imcrement。 Maybe you can try this. 也许您可以尝试一下。

INSERT INTO order_items(orderID) VALUES((SELECT id FROM orders ORDER BY id desc LIMIT 1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM