我有以下具有匹配关系的表结构:
,---------. ,--------------. ,---------.
| Threads | | ThreadsUsers | | Users |
|---------| |--------------| |---------|
| id | | id | | id |
'---------' | thread_id | '---------'
| user_id |
'--------------'
ThreadsTable 中的此自定义查询旨在查找具有给定参与者数量的线程。在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/