MySQL - 搜索自定义列

时间:2015-09-17 07:33:17

标签: mysql sql laravel laravel-5 query-builder

我想运行像这样的MySQL查询 -

 SELECT country_ID*2/id*3.159 as my_id
 FROM `state`
 WHERE my_id>2;

当我运行它时,我收到这样的错误 -

  

1054 - 'where子句'中的未知列'my_id'

在新创建的虚拟列 my_id 中搜索是否有其他替代解决方案?

实际上我正试图在 Laravel Query Builder 中进行搜索 -

  DB::table(    'project')->select( 'project.id as id',
                                    'project.completion_date as completion_date',
                                     DB::raw('FORMAT(project.total_cost_to_dispose - project.actual_cost_dispose, 2) as disposal_savings')
                                   )
                            ->where(disposal_savings>100);

我可以这样做吗?

如果没有,那么Laravel或MySQL中的解决方案是什么?

2 个答案:

答案 0 :(得分:2)

您不能在WHERE中引用别名,而是使用:

SELECT country_ID*2/id*3.159 as my_id 
FROM `state`
WHERE (country_ID*2/id*3.159)>2;

或使用子查询:

SELECT t.*
FROM
(
   SELECT country_ID*2/id*3.159 as my_id 
   FROM `state`
) as t
WHERE t.my_id>2

Simplified logical query processingSELECT几乎是最后一次,因此WHERE不了解my_id别名:

enter image description here

图片来源:https://social.technet.microsoft.com/wiki/contents/articles/20724.all-at-once-operations-in-t-sql.aspx

答案 1 :(得分:0)

在where子句中再次使用完整条件:

  DB::table(    'project')->select( 'project.id as id',
                                    'project.completion_date as completion_date',
                                     DB::raw('FORMAT(project.total_cost_to_dispose - project.actual_cost_dispose, 2) as disposal_savings')
                                   )
                            ->where FORMAT(project.total_cost_to_dispose - project.actual_cost_dispose, 2) > 100;