2016-07-20 22 views
1

我已經使用了兩張表的發票和付款。 我試圖產生付費,到期和無償狀態。應用mysql條件

以下是我的查詢,這將給所有發票和總付款。 如何應用條件來過濾已付款,到期,未付款。 我不能給作爲支付的金額 以下是成功的查詢:

select a.*, sum(b.amount) as paidamount from tbl_invoices a left join tbl_billpayment b on a.invoiceno = b.invoiceno where a.id != '' GROUP BY b.invoiceno ORDER BY a.billdate DESC LIMIT 0,10 

這將給錯誤

select a.*, sum(b.amount) as paidamount from tbl_invoices a left join tbl_billpayment b on a.invoiceno = b.invoiceno where a.id != '' and (paidamount >= a.total) 

Notice: Error: Unknown column 'paidamount' in 'where clause'

感謝您的支持

回答

0

問題出在這種情況。

(paidamount >= a.total) 

改用這樣

(sum(b.amount) >=a.total) 

paidamount只是一個別名,將取代名稱而投影。

+0

HAVING sum(b.amount)> = a.total會給我付出的結果,謝謝! –

+0

其實@dragoste的回答也是正確的.. – Ali786

2

paidamount只是在結果的別名,但它在WHERE條款中不可用。

你必須使用相同的表達sum(b.amount)取而代之的是paidamount別名

select a.*, sum(b.amount) as paidamount 
from tbl_invoices a 
left join tbl_billpayment b on a.invoiceno = b.invoiceno 
where a.id != '' and (sum(b.amount) >= a.total) 

而且這實際上將無法正常,因爲你在WHERE條款使用聚合函數工作,要麼。

WHERE發生之前分組,而SUM值每組計算。 我想你想在這裏使用HAVING子句。

select a.*, sum(b.amount) as paidamount 
from tbl_invoices a 
left join tbl_billpayment b on a.invoiceno = b.invoiceno 
where a.id != '' 
GROUP BY a.id 
HAVING sum(b.amount) >= a.total