[英]Applying mysql conditions
我使用了兩個表的發票和付款。 我試圖生成已付款,到期和未付款狀態。
以下是我的查詢,它將給出所有發票和總付款。 我如何應用條件來過濾已付款,到期,未付款。 我不能給付以下成功查詢:
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)
注意:錯誤:“ where子句”中的未知列“ paidamount”
謝謝您的支持
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
問題是在這種情況下。
( paidamount >= a.total)
代替這樣使用
(sum(b.amount) >=a.total)
paidamount只是一個別名,它將在投影時替換名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.