2015-09-17 36 views
-1

我想运行一个MySQL查询像这个 -MySQL的 - 搜索到自定义列

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

当我运行它,我越来越喜欢这个 -

1054错误 - 未知列在“where子句”添加my_id“

是否有替代的解决方案在我的新创建的虚拟列添加my_id搜索?


其实我想使这 - 像

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 Query Builder搜索?

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

回答

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

不能在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