如何使用 Balance 列的 where 子句过滤以下查询中的数据。当我在 where 条件下使用 Balance 时,出现错误 [“where 子句”中的未知列“Balance”]。
select *,(it.Total - p.Amount) as Balance
from invoices i
left outer join invoice_items it
on i.ID=it.InvoiceID
left outer join payment p
on p.InvoiceID=it.InvoiceID
where Balance!=0;
此外,当没有找到匹配的付款记录时,我需要发票项目表的总计值,而不是在余额列中显示空值。
最佳答案
不能在 where 子句中使用别名。
重写
where (it.Total - p.Amount) <> 0
其他部分
select
(case when p.PaymentId IS NULL
then it.Total
else
(it.Total - p.Amount)
end)
或者。 COALESCE 表示:如果 p.Amount 为空,则使用 0。否则使用 p.Amount
select it.Total - COALESCE(p.Amount, 0)
终于
select i.*,(it.Total - COALESCE(p.Amount, 0)) as Balance
from invoices i
left outer join invoice_items it
on i.ID=it.InvoiceID
left outer join payment p
on p.InvoiceID=it.InvoiceID
where it.Total - COALESCE(p.Amount, 0) <> 0;
关于mysql - 使用Where子句从连接的mysql表中过滤数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12472962/