我正在开发一种贷款系统,在该系统中,贷款到期时,加上利息的资金将从借款人的帐户转移到贷方。但是,只有在借款人有足够的钱这样做时,这种情况才会发生,否则到目前为止,什么也没有发生。
我有一张桌子,上面有不同的用户及其现金。
USERS
+--id--+--name--+--group--+--cash-+
另一个是每个贷款的详细信息。
LOANS
+--LoanId--+--Lender--+--lenderId--+--Borrower--+--borrowerId--+--principal--+--rate--+--term-+--due_date--+
我从借款人中扣除钱的代码(如果借款人有足够的钱)是:
$sql = "UPDATE users AS u
INNER JOIN (
SELECT l.borrowerId, SUM(l.principal + ((l.principal*l.rate*l.term)/1200)) AS total_due
FROM loans AS l
WHERE l.due_date = '2019-03-24'
GROUP BY l.borrowerId
) AS d
ON d.borrowerId = u.id
SET u.cash = CASE WHEN u.cash > d.total_due THEN u.cash - d.total_due ELSE u.cash END";
它的工作原理很好,但是当我尝试同时扣除形式上的借款人并向贷方添加资金时,我发现u.cash> d.total_due遇到了麻烦,因为它可能同时引用了贷方和借款人。
我已经尝试过了,但是不起作用:
$sql = "UPDATE users AS u
INNER JOIN (
SELECT l.lenderId, SUM(l.principal + ((l.principal*l.rate*l.term)/1200)) AS total_due
FROM loans AS l
WHERE l.due_date = '2019-03-24'
GROUP BY l.lenderId
) AS d
ON d.lenderId = u.id
INNER JOIN (
SELECT l.borrowerId
FROM loans AS l
WHERE l.LoanId = d.LoanId
GROUP BY l.lenderId
ON d.borrowerId = u.id
) AS b
SET u.cash = CASE WHEN b.cash > d.total_due THEN u.cash + d.total_due ELSE u.cash END";
非常感谢您的帮助。预先感谢!