MySQL事务自动设置计算查询

时间:2013-03-29 12:26:09

标签: mysql sql

我正在为彼此分享账单的人创建一个小型自动定位器网络应用程序。

简单的例子,如果山姆,比尔和吉姆都住在一起并分享普通账单,如电费账单,燃气账单和宽带费用,他们应该能够将每笔交易输入网络应用程序然后应用程序自动计算应该向谁支付费用。

这个问题涉及两个表:'transactions'和'transactionusers'。

交易: ID,用户ID,零售商,商品,日期

Transactionusers: ID,TransactionID,Amount,UserID

当Sam为电费账单添加“交易”记录(90美元)并将金额平均分配给室友时,3个记录被添加到'transactionusers'表中。

我希望能够编写一个SQL查询来计算所有用户之间所有交易的总和,然后取消反向交易(如果Sam欠Bill 50,Bill欠Sam 20美元,那么和解就是Bill欠Sam $ 30)

我当前的查询允许您总结每对用户之间的总交易价值,但不会带走反向交易 - 任何帮助非常感谢:

SELECT transactionusers.userID AS debtor, SUM(amount) AS owes, transactions.userID AS toUser FROM transactionusers
INNER JOIN transactions ON transactions.ID = transactionusers.transactionID
WHERE transactions.userID <> transactionusers.userID
GROUP BY transactionusers.userID, transactions.userID

示例数据

假设UserID是Sam(1),Bill(2),Jim(3)

交易:

1, 1, 'Electricity Co', 'Electricity Bill'
2, 2, 'Gas Co', 'Gas Bill'
3, 3, 'Broadband Co', 'Broadband Charge'

Transactionusers:

1, 1, 30, 1
2, 1, 30, 2
3, 1, 30, 3

4, 2, 20, 1
5, 2, 20, 2
6, 2, 20, 3

7, 3, 5, 1
8, 3, 5, 2
9, 3, 5, 3

示例记录中未显示的是能够在用户之间不平等地拆分账单;例如:如果吉姆一个月住在房子里,他可能会收到更多的账单

1 个答案:

答案 0 :(得分:0)

您的查询很好,您只需要对同一个查询进行联接并扣除结果:

SELECT transactionusers.userID AS debtor, IF(SUM(amount)-r.owes < 0, 0, SUM(amount)-r.owes) AS owes, transactions.userID AS toUser FROM transactionusers
INNER JOIN transactions ON transactions.ID = transactionusers.transactionID
LEFT JOIN (
    SELECT transactionusers.userID AS debtor, SUM(amount) AS owes, transactions.userID AS toUser FROM transactionusers
    INNER JOIN transactions ON transactions.ID = transactionusers.transactionID
    WHERE transactions.userID <> transactionusers.userID
    GROUP BY transactionusers.userID, transactions.userID
) r ON r.debtor = transactions.userID AND r.toUser = transactionusers.userID
WHERE transactions.userID <> transactionusers.userID
GROUP BY transactionusers.userID, transactions.userID