postgresql - 在 PostgreSQL 上,Cakephp 3 查询中的having(count) 失败

标签 postgresql cakephp

我有以下具有匹配关系的表结构:

   ,---------.   ,--------------.    ,---------.
   | Threads |   | ThreadsUsers |    |  Users  |
   |---------|   |--------------|    |---------|
   |   id    |   |      id      |    |    id   |
   '---------'   |  thread_id   |    '---------'
                 |    user_id   |
                 '--------------'

ThreadsT​​able 中的此自定义查询旨在查找具有给定参与者数量的线程。在mysql上运行良好

public function findWithUserCount(Query $query, array $options)
{
    return $query
        ->matching('Users')
        ->select([
            'Threads.id',
            'count' => 'COUNT(Users.id)'
        ])
        ->group('Threads.id HAVING count = ' . $options['count']);
}

但是在 postgresql 上失败并出现以下错误

PDOException: SQLSTATE[42703]: Undefined column: 7 
       ERROR: column "count" does not exist
LINE 1: ...ThreadsUsers.user_id)) GROUP BY Threads.id HAVING count = 2

最佳答案

HAVING 子句无法引用 SELECT 子句中定义的列别名。 documentation says :

Each column referenced in condition must unambiguously reference a grouping column, unless the reference appears within an aggregate function or the ungrouped column is functionally dependent on the grouping columns.

由于 count 既不是“分组列”(即 GROUP BY 子句的主题)也不是聚合函数,因此不能在那里使用它。

因此,正确的形式可能是(我不了解 CakePHP,事实上,您可以将 SQL 注入(inject)到 group 调用中,这对于查询构建器来说似乎是一个严重损坏的设计) :

->group('Threads.id HAVING COUNT(Users.id) = ' . $options['count']);

关于postgresql - 在 PostgreSQL 上,Cakephp 3 查询中的having(count) 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30395998/

相关文章:

cakephp - 在 CakePHP 中向 Containable 添加条件

php - ZF2 如何获取最后插入的 id 值?

json - PostgreSQL 9.5 - 将 NULL 与 JSON 合并时更新不起作用

sql - 显示在结果中匹配的参数

forms - cakePHP 表单输入标签覆盖 inputDefaults

mysql - 将 MySql 查询转换为 Cakephp 2.6

php - cakephp 无法使用 set 更新表

php - 在 CakePhp 中组合数组

javascript - 如何将用户创建的复选框值传递到另一个页面?

sql - PostgreSQL 9.3 : Filter in Pivot table query