我试图在WHERE子句中进行简单的减法工作,我有以下内容:
SELECT account, SUM(payments) AS total_payments, amount_due FROM clients
LEFT JOIN payments ON clients.id = payments.id
LEFT JOIN account_details ON clients.id = account_details.id
WHERE account_details.amount_due - SUM(payments) < 0
我做错了什么?
答案 0 :(得分:1)
您不能在where子句中使用SUM。 试试这个:
SELECT account, SUM(payments) AS total_payments, amount_due FROM clients
LEFT JOIN payments ON clients.id = payments.id
LEFT JOIN account_details ON clients.id = account_details.id
GROUP BY account
HAVING SUM(payments) < 0;
答案 1 :(得分:0)
你可以这样做,但无论如何它不是最佳查询。
SELECT a.* from
(SELECT account, SUM(payments) AS total_payments, amount_due FROM clients
LEFT JOIN payments ON clients.id = payments.id)as a
LEFT JOIN account_details ON clients.id = account_details.id
WHERE account_details.amount_due - a.total_payments < 0