mysql – 使用2个别名的数学结果创建别名

前端之家收集整理的这篇文章主要介绍了mysql – 使用2个别名的数学结果创建别名前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我试图减去2个别名,以便创建另一个别名,但我得到一个“未知列”错误.

这是我的sql

select o.id,o.name,(select sum(l.source_expense)
        from `assignments` as a
        left join `leads` as l on (l.id = a.lead_id)
        where a.{$this->sql_column}=o.id
        and l.date_created between {$this->date_from} and {$this->date_to}
        and find_in_set(l.vertical_id,'".implode(',',$this->app_user->verticals)."')
     ) as `expense`,(select sum(a.buyer_revenue)
        from `assignments` as a
        left join `leads` as l on (l.id = a.lead_id)
        where a.refunded=0
        and a.{$this->sql_column}=o.id
        and l.date_created between {$this->date_from} and {$this->date_to}
        and find_in_set(l.vertical_id,$this->app_user->verticals)."')
     ) as `revenue`,`revenue` - `expense` as `profit`
     from {$this->sql_table} as o

基本上,我想通过从费用中减去收入来创建利润别名.原因是我正在使用数据表并希望列可以排序.我已经知道我可以用PHP轻松做到这一点.

我怎么能做到这一点?

编辑 – 我尝试了下面的答案,并从PHPStorm获得“每个派生表应该有别名”错误,并在尝试运行查询时出现语法错误.

继承人新的查询

select t.id,t.name,t.expense,t.revenue,t.revenue - t.expense as profit
from(select o.id,$this->app_user->verticals)."')
     ) as `revenue`
     from {$this->sql_table} as o
 ) as t
最佳答案
只需用另一个select包装它,然后别名将可用于数学计算:

SELECT t.id,t.revenue -t.expense as `profit`
FROM (Your Query Here) t
原文链接:https://www.f2er.com/mysql/432868.html

猜你在找的MySQL相关文章