为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕桂英4014372 2023-10-15 16:33:28
      $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 查询中使用 daypercentage,则无法找到它。在这种情况下怎么可能呢?
查看完整描述

1 回答

?
泛舟湖上清波郎朗

TA贡献1818条经验 获得超3个赞

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

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

where users_24h >= users_48h_24h

我不确定用 Lavarel 表达这一点的最佳方式是什么,也许:

->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'))

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


查看完整回答
反对 回复 2023-10-15
  • 1 回答
  • 0 关注
  • 66 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信