mysql - 使用Where子句从连接的mysql表中过滤数据

标签 mysql

如何使用 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/

相关文章:

mysql - SQL NOT IN 结果不符合预期

mysql - 非原子行为 Eclipselink-半提交的数据库事务

php - Foreach 嵌套在带有 PDO 查询的 while 循环中

mysql - ON DUPLICATE KEY UPDATE - 添加到现有值

php - 如何使用相同的查询插入数据

php - 使用 PHP 和 MySQL 检查页面命中情况?

mysql - 在 WHERE 语句中添加和比较列

php - exec ("mysqldump") 返回 2 但该命令在命令行中工作

mysql - 存储多个时间戳和数字的最佳方式?

php - 在比较另一个表的值并搜索值是否存在于表的字段内之后更新平板电脑的字段