假设您的面包店业务有三张 table :
online_order
invoice
customer_id
您的老板调用您说“我需要为我们所有的客户订购一个巧克力蛋糕,还要为他们单独开具发票”。所以现在你必须做两件事:
- 为每个客户创建一个
online_order
条目 - 然后为该订单开具发票。
但是,每个客户都需要有自己的在线订单号,他们可以在发票上引用该编号。
如何在一次交易中做到这一点?以下是我所拥有的(伪代码),但我会向您展示我的输出和预期输出。
BEGIN;
-- First lets create the order
INSERT INTO online_order (online_order_id, date, cake_type, cake_flavor)
VALUES
(AUTO_INCREMENT, NOW(), round, chocolate);
-- Then take that online_order_id and create an invoice out of it for one of our customers
INSERT INTO invoice (date, online_order_id, invoice_amt, customer_id)
SELECT
NOW(),
LAST_INSERT_ID(),
10.00,
CUSTOMER_ID
FROM CUSTOMER;
ROLLBACK;
END;
我的输出
-- Let's say the next auto-incremented online_order_id is 10011:
INSERT INTO invoice VALUES ("2016-01-01", 10011, 10.00, "1");
INSERT INTO invoice VALUES ("2016-01-01", 10011, 10.00, "2");
INSERT INTO invoice VALUES ("2016-01-01", 10011, 10.00, "3");
INSERT INTO invoice VALUES ("2016-01-01", 10011, 10.00, "4");
INSERT INTO invoice VALUES ("2016-01-01", 10011, 10.00, "5");
期望的输出(每张发票有不同的online_order_id
)
INSERT INTO invoice VALUES ("2016-01-01", 10011, 10.00, "1");
INSERT INTO invoice VALUES ("2016-01-01", 10012, 10.00, "2");
INSERT INTO invoice VALUES ("2016-01-01", 10013, 10.00, "3");
INSERT INTO invoice VALUES ("2016-01-01", 10014, 10.00, "4");
INSERT INTO invoice VALUES ("2016-01-01", 10015, 10.00, "5");
我需要为每个客户插入订单,然后插入发票,然后插入订单,然后插入发票……。我怎么能在MySQL中写这个?谢谢!
最佳答案
您可以创建一个表来维护不同实体的 ID
并使用 SELECT.. FOR UPDATE
获取原子值。表格看起来像这样:
Entity | Value
Order | 1
Blah | 2
然后您可以使用以下代码块获取新 ID:
set @id := select value from Ids where Entity = 'Order' FOR UPDATE;
update Ids set value = value + 1 Enity = 'Order';
commit;
这将为您提供 ID 并将其递增 1。然后可以在 invoide
表中使用此 ID。
因为您将使用 select.. for update
,相应的行将被锁定,并且没有其他事务能够读取/修改该值,从而实现原子性。
如果并行执行的插入过多,这种方法可能会成为瓶颈。
关于MySQL在一个具有依赖关系的事务中有两个插入语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41252119/