当我想对 total_debtor_price
和 total_debtor_price
使用 Where
子句时,我收到以下错误消息:
Unable to resolve column
total_debtor_price
(ortotal_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/