这是我的疑问:
SELECT c.remaining_budget,
c.future_liabilities,
c.used_this_month,
bi.full_name,
bi.id AS
item_id,
(SELECT Sum(amount)
FROM balance_histories
WHERE balance_histories.budget_item_id = 21
AND Date_format(payment_date, '%Y-%m-01') = '2018-01-01') AS
monthly_usage
FROM families_budget_items_calcs c
LEFT JOIN budget_items bi
ON c.budget_item_id = bi.id
WHERE c.family_id = 54824
AND bi.id IN ( 21 )
AND monthly_usage <> 0
当我执行此查询时,我收到一个错误: WHERE子句中的未知列'monthly_usage'。
为什么呢?它在那里!
答案 0 :(得分:2)
问题是由于在评估monthly_usage
子句时,您在select子句中定义的别名WHERE
不可用。此处的一个直接解决方法是将monthly_usage
上的检查移至HAVING
子句:
WHERE
c.family_id = 54824 AND
bi.id IN ( 21 )
HAVING
monthly_usage <> 0
如果您不想这样做,那么您可以在WHERE
子句中重复使用子查询进行月度使用。
答案 1 :(得分:1)
SELECT c.remaining_budget, c.future_liabilities, c.used_this_month,
bi.full_name, bi.id as item_id,
(SELECT Sum(bh.amount)
FROM balance_histories bh
WHERE bh.budget_item_id = 21 AND
payment_date >= '2018-01-01' AND
payment_date < '2018-02-01'
) as monthly_usage
FROM families_budget_items_calcs c INNER JOIN
budget_items bi
ON c.budget_item_id = bi.id
WHERE c.family_id = 54824 AND
bi.id IN ( 21 )
HAVING monthly_usage <> 0 ;
注意:
WHERE
子句将外连接转换为内连接,因此指定LEFT JOIN
会产生误导。USING
)。date_format()
等功能。首先,很难遵循逻辑。其次,它阻止使用索引。