Php Laravel,如何在where查询中使用select AS?

Php Laravel,如何在where查询中使用select AS?,php,mysql,sql,laravel,laravel-5,Php,Mysql,Sql,Laravel,Laravel 5,如果我在where查询中使用daypercentage,则无法找到它。在这种情况下怎么可能呢?在SQL中,select子句中定义的别名不能在where子句中重用。您需要重复表达式(或使用子查询或cte) MySQL有一个技巧,允许在having子句中使用别名,但我不建议在这里使用别名。您似乎只想要非负百分比,因此我认为您的where子句可以简化为: $data['losers'] = $data['losers'] ->select(DB::raw(

如果我在where查询中使用daypercentage,则无法找到它。在这种情况下怎么可能呢?

在SQL中,
select
子句中定义的别名不能在
where
子句中重用。您需要重复表达式(或使用子查询或cte)

MySQL有一个技巧,允许在
having
子句中使用别名,但我不建议在这里使用别名。您似乎只想要非负百分比,因此我认为您的
where
子句可以简化为:

        $data['losers'] = $data['losers']
            ->select(DB::raw('ROUND((((users_24h-users_48h_24h) / users_48h_24h) * 100),2) AS daypercentage, name'))
            ->where('daypercentage', '>=', '0')
我不确定用拉瓦雷尔表达这一点的最佳方式是什么,也许:

where users_24h >= users_48h_24h

请注意,我删除了
round()
表达式中一些不必要的括号。

这段代码有什么错误?另外,请发布未找到的
$data['losers']
列:在'where子句'$data['losers']中的1054未知列'daypercentage'是一组数据,关键是我在select中用2整数计算daypercentage。没有where查询,一切都可以工作。但是如果我尝试过滤错误的准确率。我猜选择中的“AS”不能用在where中,问题是我如何使用它。我猜有两个计算,但一个更好。尝试在通过phpMyAdmin或workbench运行的查询中使用别名。您会发现别名不能在whereQuery builder语法中使用:
->where('users\u 24h','>=','users\u 48h\u 24h')
->select(DB::raw('round( (users_24h - users_48h_24h) / users_48h_24h * 100,2) as daypercentage, name'))
->where(DB::raw('users_24h >= users_48h_24h'))