MySQL - 搜索自定义列

MySQL - Search into a custom Column

我想运行一个MySQL这样的查询-

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

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

1054 - Unknown column 'my_id' in 'where clause'

在我新创建的虚拟列 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的解决方案是什么?

您不能在 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 别名:

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

在 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;