【问题标题】:Error when using "ALL" operator when execute query执行查询时使用“ALL”运算符时出错
【发布时间】:2019-03-04 13:37:28
【问题描述】:

我需要使用 phalcon 框架执行以下查询: “从表 GROUP BY 中选择 id HAVING '31' = ALL(array_agg(status))” 如何使用 phalcon 执行此查询? 当我执行以下操作时:

 Model::query()
   ->columns(['id'])
   ->groupBy('id')
   ->having('31 = ALL(array_agg(status))')
   ->execute();

我收到以下错误消息: 语法错误,意外标记 ALL,靠近 '(array_agg(status))',解析时:SELECT id FROM [SomeNameSpace\Model] GROUP BY [id] HAVING 31 = ALL(array_agg(status)) (137)

【问题讨论】:

    标签: postgresql phalcon


    【解决方案1】:

    我不确定 100% 支持哪些 Postgres 函数,但您可以这样尝试:

    Model::query()
        ->columns([
            'id',
            'ALL(array_agg(status)) AS statusCounter'
        ])
        ->groupBy('id')
        ->having('31 = statusCounter')
        ->execute();
    

    请注意,我在选择中移动了聚合函数,而不是在 having 子句中。


    更新:这里是一个非常自定义的查询示例。不支持使用的大多数函数,有时只需编写一个简单的 SQL 查询并将所需的模型绑定到它就更简洁了:

    public static function findNearest($params = null)
    {
        // A raw SQL statement
        $sql = '
            SELECT *, 111.045 * DEGREES(ACOS(COS(RADIANS(:lat))
             * COS(RADIANS(X(coords)))
             * COS(RADIANS(Y(coords)) - RADIANS(:lng))
             + SIN(RADIANS(:lat))
             * SIN(RADIANS(X(coords)))))
             AS distance_in_km
            FROM object_locations
            ORDER BY distance_in_km ASC
            LIMIT 0,5;    
        ';
    
        // Base model
        $model = new ObjectLocations();
    
        // Execute the query
        return new \Phalcon\Mvc\Model\Resultset\Simple(
            null,
            $model,
            $model->getReadConnection()->query($sql, $params)
        );
    }
    
    // How to use:
    \Models\ObjectLocations::findNearest([
        'lat' => 42.4961756,
        'lng' => 27.471543300000008
    ])
    

    【讨论】:

      【解决方案2】:

      您需要将 ALL 添加为方言扩展名。检查此主题,例如https://forum.phalconphp.com/discussion/16363/where-yearcurrenttimestamp-how-to-do-this

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-27
        • 2018-12-14
        • 2012-11-04
        • 2012-07-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多