【发布时间】:2021-01-16 18:59:03
【问题描述】:
我有一个查询生成器来选择过去 12 个月内创建的所有用户
$range = \Carbon\Carbon::now()->subYears(1);
$countUser = DB::table('users')
->select(DB::raw('month(created_at) as getMonth'),
DB::raw('year(created_at) as getYear'),
DB::raw('COUNT(*) as value'))
->where('created_at', '>=', $range)
->groupBy('getMonth','getYear')
->orderBy('getMonth', 'ASC')
->get();
这个查询在 MySQL 上运行良好,但是,当我将它部署在运行 PostgreSQL 数据库的 Heroku 上时,它返回一个错误
列 "getMonth" 不存在 LINE 1: ...end date)", "extract(year from created_at)" order by "getMonth"... ^ (SQL: select extract(month from created_at) as getMonth ,提取(从 created_at 中提取的年份)作为 getYear,计数(*)作为来自“用户”的值,其中“created_at”> = 2019-10-01 03:16:43 分组为“提取(来自 created_at 的月份)”,“提取( year from created_at)" order by "getMonth" asc)
我尝试搜索并发现 postgest 有一个不同的语句来获取 created_at 列中的月份和年份,我将我的代码更改为此,它还返回错误未找到列 getMonth GroupBy()
$range = \Carbon\Carbon::now()->subYears(1);
$countUser = DB::table('users')
->select(DB::raw('extract(month from created_at) as getMonth'),
DB::raw('extract(year from created_at) as getYear'),
DB::raw('COUNT(*) as value'))
->where('created_at', '>=', $range)
->groupBy('getMonth','getYear')
->orderBy('getMonth', 'ASC')
->get();
PostgreSQL 是否有任何命名规则来为选定的列设置名称,或者它有什么方法可以解决我的问题? 感谢阅读!
【问题讨论】:
-
@WaytoDeveloper 是吗?你有关于 getMonth 信息的链接吗?
标签: php laravel postgresql