解决PG :: GroupingError:错误

时间:2015-09-21 19:13:39

标签: ruby-on-rails postgresql ruby-on-rails-4 activerecord

以下代码获取residences中列出amenities所有id_list的所有id_list = [48, 49] Residence.joins(:listed_amenities). where(listed_amenities: {amenity_id: id_list}). references(:listed_amenities). group(:residence_id). having("count(*) = ?", id_list.size) 。它可以解决SQLite的问题,但会引发PostgreSQL的错误:

concat

PostgreSQL版本的错误:

Rails error message

我需要更改什么才能使其与PostgreSQL一起使用?

2 个答案:

答案 0 :(得分:1)

一些事情:

  1. references只能与includes一起使用;它告诉ActiveRecord执行连接,因此在使用显式joins时它是多余的。

  2. 您需要将参数完全限定为group,即group('residences.id')

  3. 例如,

    id_list = [48, 49]
    Residence.joins(:listed_amenities).
              where(listed_amenities: { amenity_id: id_list }).
              group('residences.id').
              having('COUNT(*) = ?", id_list.size)
    

答案 1 :(得分:1)

Ruby(?)代码扩展到的查询是从住宅表中选择所有字段:

SELECT "residences".*
  FROM "residences"
 INNER JOIN "listed_amenities"
    ON "listed_amentities"."residence_id" = "residences"."id"
 WHERE "listed_amenities"."amenity_id" IN (48,49)
 GROUP BY "residence_id"
HAVING count(*) = 2
 ORDER BY "residences"."id" ASC
 LIMIT 1;

Postgres manual开始,当存在GROUP BY时,SELECT列表表达式无法引用除聚合函数之外的未分组列,或者未分组列在功能上依赖于分组列,因为那里否则,对于未分组的列,将返回多个可能的值。

您需要按聚合函数未应用的所有字段进行分组,或者以不同方式执行此操作。从查询中,您似乎只需要扫描amentities表以获取您正在寻找的住所ID:

SELECT "residence_id"
  FROM "listed_amenities"
 WHERE "listed_amenities"."amenity_id" IN (48,49)
 GROUP BY "residence_id"
HAVING count(*) = 2
 ORDER BY "residences"."id" ASC
 LIMIT 1

然后使用该ID获取您的住所数据。或者,在一个查询中:

SELECT "residences".*
  FROM "residences"
 WHERE "id" IN (SELECT "residence_id"
                  FROM "listed_amenities"
                 WHERE "listed_amenities"."amenity_id" IN (48,49)
                 GROUP BY "residence_id"
                HAVING count(*) = 2
                 ORDER BY "residences"."id" ASC
                 LIMIT 1
               );