MySQL 我的查询中的未知列

MySQL unknown column in my query

我有以下 MySQL 查询

select 
    keliones_lapas.Vairuot_Id, 
    MONTH(keliones_lapas.Data_darbo), 
    sum(keliones_lapas.uzdarbis) as Got, 
    coalesce(Suma, 0) Suma, 
    (sum(keliones_lapas.uzdarbis) - coalesce(Suma, 0)) Total
from keliones_lapas
left join (select Vairuotas, MONTH(Data_islaidu), sum(Suma) as Spend from 
    islaidos group by Vairuotas, MONTH(Data_islaidu))
    islaidos on 
    keliones_lapas.Vairuot_Id=islaidos.Vairuotas and 
    MONTH(keliones_lapas.Data_darbo)=MONTH(islaidos.Data_islaidu)
group by keliones_lapas.Vairuot_Id, MONTH(keliones_lapas.Data_darbo), Suma
order by keliones_lapas.Vairuot_Id, MONTH(keliones_lapas.Data_darbo);

我收到这个错误:

1054 - 'field list'

中的未知列 'Suma'

我知道这个问题是已知的,但我不知道如何自行解决。 This is the cause of the issue which is solved

我可以提供 fiddle : http://sqlfiddle.com/#!9/e76ef9/8

您只需为子查询中的所有计算列设置别名,然后您就可以在ON 子句中引用这些别名。这是来自 fiddle 的 SQL,Data_islaidu 和 Suma 列别名:

select keliones_lapas.Vairuot_Id, MONTH(keliones_lapas.Data_darbo), sum(keliones_lapas.uzdarbis) as Got, coalesce(Suma, 0) AS Spend, (sum(keliones_lapas.uzdarbis) - coalesce(Suma, 0)) Total
from keliones_lapas
left join (
    select 
        Vairuotas, 
        MONTH(Data_islaidu) as Data_islaidu, 
        sum(Suma) as Suma 
     from islaidos 
     group by Vairuotas, MONTH(Data_islaidu)) islaidos 
on keliones_lapas.Vairuot_Id = islaidos.Vairuotas 
and MONTH(keliones_lapas.Data_darbo) = MONTH(islaidos.Data_islaidu)
group by keliones_lapas.Vairuot_Id, MONTH(keliones_lapas.Data_darbo), Suma
order by keliones_lapas.Vairuot_Id, MONTH(keliones_lapas.Data_darbo);