【问题标题】:Laravel, how to use select AS in where query? [duplicate]Laravel,如何在 where 查询中使用 select AS? [复制]
【发布时间】:2020-12-06 20:53:59
【问题描述】:
        $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,则找不到。在这种情况下怎么可能?

【问题讨论】:

  • 这段代码有什么错误?也请张贴$data['losers']是什么@
  • 未找到列:1054 'where 子句' $data['losers'] 中的未知列 'daypercentage' 是一堆数据,关键是我在我的选择中用 2 个整数计算 daypercentage。没有 where 查询一切正常。但是,如果我尝试过滤错误发生的日期百分比。我猜选择中的“AS”不能在哪里使用,问题是我如何能够使用它。我的猜测是进行 2 次计算,但有一次会更好。
  • 尝试在通过 phpMyAdmin 或工作台运行的查询中使用别名。你会发现在where中不能使用别名

标签: php mysql sql laravel laravel-5


【解决方案1】:

在 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() 表达式中的一些不必要的括号。

【讨论】:

  • 查询生成器语法:->where('users_24h', '>=', 'users_48h_24h')
猜你喜欢
  • 2013-01-05
  • 2013-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-18
  • 1970-01-01
  • 2020-09-15
相关资源
最近更新 更多