在 Cakephp 3 查询中拥有(计数)在 PostgreSQL 上失败
Having(count) in a Cakephp 3 query fails on PostgreSQL
我有以下 table 具有匹配关系的结构:
,---------. ,--------------. ,---------.
| 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
既不是 "grouping column"(即 GROUP BY
子句的主题)也不是聚合函数,因此不能在那里使用。
所以正确的形式大概是(我不知道 CakePHP,而且你可以将 SQL 注入 group
调用这一事实似乎是一个严重破坏的设计查询生成器):
->group('Threads.id HAVING COUNT(Users.id) = ' . $options['count']);
我有以下 table 具有匹配关系的结构:
,---------. ,--------------. ,---------.
| 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
既不是 "grouping column"(即 GROUP BY
子句的主题)也不是聚合函数,因此不能在那里使用。
所以正确的形式大概是(我不知道 CakePHP,而且你可以将 SQL 注入 group
调用这一事实似乎是一个严重破坏的设计查询生成器):
->group('Threads.id HAVING COUNT(Users.id) = ' . $options['count']);