【问题标题】:#1054 - Unknown column in 'field list'#1054 - “字段列表”中的未知列
【发布时间】:2014-11-04 06:32:26
【问题描述】:

我又遇到了另一个问题。我知道有很多与此问题相关的链接,但无法为我的查询找到确切的解决方案。这是我的查询:-

SELECT c.cust_id, c.cust_name, c.cust_mob, sum(CASE WHEN trans_type = 'Purchase' THEN total_amt ELSE 0 END) as purchase, sum(CASE WHEN trans_type = 'Sale' THEN total_amt ELSE 0 END) as sale, sum(ifnull(a.payment_amt,0)) as tot_pay, (purchase-(sale+sum(a.payment_amt))) as tot_torcv, ((sale+sum(a.payment_amt))-purchase) as tot_topay FROM bil_customers c 
    inner join bil_vendor_account a on(c.cust_id=a.vendor_id) 
    WHERE c.cust_catagory = '3' 
    group by cust_id 
    having ifnull(tot_torcv,0) between '0' and '100000' 
    order by a.sl_no

我不知道查询有什么问题,因为它抛出以下错误:-

1054 - “字段列表”中的未知列“购买”

请帮我解决问题。提前致谢!!

【问题讨论】:

  • 你不能这样使用别名。

标签: mysql


【解决方案1】:

您的错误是,您将购买用作列,即使它是别名,您也可以改用它

未测试

SELECT c.cust_id, c.cust_name, c.cust_mob, @purchase :=sum(CASE WHEN trans_type = 'Purchase' THEN total_amt ELSE 0 END) as purchase, sum(CASE WHEN trans_type = 'Sale' THEN total_amt ELSE 0 END) as sale, sum(ifnull(a.payment_amt,0)) as tot_pay, (@purchase-(sale+sum(a.payment_amt))) as tot_torcv, ((sale+sum(a.payment_amt))-@purchase) as tot_topay FROM bil_customers c 
inner join bil_vendor_account a on(c.cust_id=a.vendor_id) 
WHERE c.cust_catagory = '3' 
group by cust_id 
having ifnull(tot_torcv,0) between '0' and '100000' 
order by a.sl_no

如果我错过了什么,请告诉我

【讨论】:

  • 非常感谢@CodeSlayer。我用计算替换了购买和销售别名,它工作得很好。 :) 但是我可以知道为什么别名不能用作另一列吗?
  • 别名和列名不起作用我不知道为什么可能是因为它们是动态数据,因此您需要将其存储在变量中以获取列的当前值。
  • 既然我的回答解决了你的问题,你能把它标记为解决方案吗?
【解决方案2】:

您不能在 select 语句中使用别名 createtd 来计算其他列。你必须用计算替换别名

SELECT c.cust_id, c.cust_name, c.cust_mob, sum(CASE WHEN trans_type = 'Purchase' THEN total_amt ELSE 0 END) as purchase, sum(CASE WHEN trans_type = 'Sale' THEN total_amt ELSE 0 END) as sale, sum(ifnull(a.payment_amt,0)) as tot_pay, (sum(CASE WHEN trans_type = 'Purchase' THEN total_amt ELSE 0 END)-(sale+sum(a.payment_amt))) as tot_torcv, ((sale+sum(a.payment_amt))-sum(CASE WHEN trans_type = 'Purchase' THEN total_amt ELSE 0 END)) as tot_topay FROM bil_customers c 
    inner join bil_vendor_account a on(c.cust_id=a.vendor_id) 
    WHERE c.cust_catagory = '3' 
    group by cust_id 
    having ifnull(tot_torcv,0) between '0' and '100000' 
    order by a.sl_no

【讨论】:

    【解决方案3】:

    除了 CodeSlays 所写的内容之外,<expression> between '0' and '100000' 将无法按您的预期工作,因为它将执行字符串比较而不是数字比较(提醒:'9' > '10',)。

    【讨论】:

      猜你喜欢
      • 2020-10-27
      • 2018-10-21
      • 2021-01-26
      • 2014-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-05
      相关资源
      最近更新 更多