【问题标题】:How to select and order an extracted column in PostgreSQL如何在 PostgreSQL 中选择和排序提取的列
【发布时间】: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


【解决方案1】:

如果你在 postgresql 中使用混合大小写的别名,它们必须被引用。使用 get_month 代替 getMonth,或使用 AS "getMonth"groupBy('"getMonth"',...

【讨论】:

    猜你喜欢
    • 2019-03-28
    • 1970-01-01
    • 2023-02-11
    • 2016-08-31
    • 2019-05-09
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多