Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Where子句从联接的mysql表筛选数据_Mysql - Fatal编程技术网

使用Where子句从联接的mysql表筛选数据

使用Where子句从联接的mysql表筛选数据,mysql,Mysql,如何使用余额列的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.InvoiceI

如何使用余额列的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
或者。合并意味着:如果p.金额为空,则使用0。否则使用p.金额

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;
选择i.*(it.Total-COALESCE(p.Amount,0))作为余额
从发票一
左外连接发票\u项目吗
on i.ID=it.InvoiceID
左外联接
on p.InvoiceID=it.InvoiceID
式中,总-聚结(p.Amount,0)0;
试试这个:

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 (it.Total - p.Amount) <> 0;
选择*,(it.Total-p.Amount)作为余额
从发票一
左外连接发票\u项目吗
on i.ID=it.InvoiceID
左外联接
on p.InvoiceID=it.InvoiceID
其中(it.Total-p.Amount)0;
不能在where子句中使用别名,因为按时间顺序,where发生在SELECT之前,这始终是执行链中的最后一步。

where(it.Total-p.Amount)!=0;应该可以工作:
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 (it.Total - p.Amount) <> 0;