如何连接插入未知 ID 的两行

How do I connect two rows inserted with unknown id

我的这个系统有一些会计功能。假设有两个账户,我想在这两个账户之间转账。 acc1(id 1)acc2(id 2)。所以我想从 1 向 2 转账。我有这笔交易 table。对于此次转账,我向交易 table 插入了两行。第一笔交易从 acc1 取钱,第二笔交易将这笔钱存入 acc2。如何连接这两个交易?我需要另一个 id,这两个 id 是相同的。 TransactionID字段是自动递增的,我不知道id是多少。我可以在 mod 10000 中创建一个随机数序列,但每次我都必须检查是否存在使用生成的 ID 的交易。感谢您的帮助。

你可以有一个新的 table Transfers。就像:

CREATE TABLE Transfers (
    id INT AUTO_INCREMENT PRIMARY KEY,
    from_transaction_id INT,
    to_transaction_id INT,
    UNIQUE INDEX from_to (from_transaction_id, to_transaction_id),
    FOREIGN KEY from_transaction_id REFERENCES Transactions (id),
    FOREIGN KEY to_transaction_id REFERENCES Transactions (id)
);

将取款和存款交易添加到 Transactions table 后,您可以将这两个交易的 ID 添加到 Transfers 行。