【问题标题】:Applying mysql conditions应用mysql条件
【发布时间】:2016-07-20 08:45:36
【问题描述】:

我使用了两张表发票和付款。 我尝试生成已付款、到期和未付款状态。

以下是我的查询,这将提供所有发票和总付款。 我如何应用条件来过滤已付、到期、未付。 我不能给付金额 以下为查询成功:

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”

感谢您的支持

【问题讨论】:

    标签: mysql


    【解决方案1】:

    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
    

    【讨论】:

      【解决方案2】:

      问题就在这种情况下。

      ( paidamount >= a.total)
      

      改为这样使用

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

      paidamount 只是一个别名,将在投影时替换 name。

      【讨论】:

      • HAVING sum(b.amount) >= a.total 会给我付费结果,谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-26
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多