mysql - 当我使用另一个表的 SUM 时无法解析列

标签 mysql sql

当我想对 total_debtor_pricetotal_debtor_price 使用 Where 子句时,我收到以下错误消息:

Unable to resolve column total_debtor_price (or total_creditor_price);

我的查询在没有 where 子句的情况下工作正常。

DROP TEMPORARY TABLE IF EXISTS tmp_AccountingDocument_datatable;

CREATE TEMPORARY TABLE tmp_AccountingDocument_datatable
SELECT 
  TAD.*,
  (
    SELECT SUM(TADD.debtor_price) AS total_debtor_price 
    FROM Vw_AccountingDocumentDetail TADD 
    WHERE TADD.accounting_document_id = TAD.id
  ) total_debtor_price,
  (
    SELECT SUM(TADD.creditor_price) AS total_creditor_price 
    FROM Vw_AccountingDocumentDetail TADD 
    WHERE TADD.accounting_document_id = TAD.id
  ) total_creditor_price
FROM Tb_Accounting_Documents TAD
WHERE IF(
  NOT ISNULL(_Filter_Price_Status),
  CASE
    WHEN _Filter_Price_Status = 'smaller' 
      THEN (
        total_debtor_price <= _Filter_Price OR 
        total_creditor_price <= _Filter_Price
      )
    WHEN _Filter_Price_Status = 'equal' 
      THEN (
        total_debtor_price = _Filter_Price OR 
        total_creditor_price = _Filter_Price
      )
    WHEN _Filter_Price_Status = 'bigger' 
      THEN (
        total_debtor_price >= _Filter_Price OR 
        total_creditor_price >= _Filter_Price
      )
  END,
  TRUE
)

最佳答案

不能在where子句中使用列别名,但可以将主查询放入子查询中,以便使用带有列别名的where子句

 SELECT * FROM (
    SELECT TAD.*,(SELECT SUM(TADD.debtor_price) as total_debtor_price FROM Vw_AccountingDocumentDetail TADD WHERE TADD.accounting_document_id = TAD.id) total_debtor_price,
           (SELECT SUM(TADD.creditor_price) as total_creditor_price FROM Vw_AccountingDocumentDetail TADD WHERE TADD.accounting_document_id = TAD.id) total_creditor_price
        FROM Tb_Accounting_Documents TAD
  ) TMP
    WHERE
    IF(NOT isnull(_Filter_Price_Status),
             CASE
                 WHEN _Filter_Price_Status = 'smaller' THEN (total_debtor_price <= _Filter_Price OR total_creditor_price <= _Filter_Price)
                 WHEN _Filter_Price_Status = 'equal' THEN (total_debtor_price = _Filter_Price OR total_creditor_price = _Filter_Price)
                 WHEN _Filter_Price_Status = 'bigger' THEN (total_debtor_price >= _Filter_Price OR total_creditor_price >= _Filter_Price)
                 END, TRUE)

关于mysql - 当我使用另一个表的 SUM 时无法解析列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57986041/

相关文章:

sql - 按拆分列排序

mysql - UTF-8字符有问题;我看到的不是我存储的

php - 选择时将不存在的字段设置为值

javascript - Node.JS + MySQL - 结合定义变量和选择数据的查询

SQL Server : Count the number of times the ID from table A occurs in table B

sql - 如何从特定点开始自动递增?

mysql - 如何计算 mysql 程序中的内容?

php - 为什么不自动创建关系表? (在mysql中)

mysql - 在单个查询中更新相同的 mysql 字段两次

mysql - 第一个非假值