使用 group by 的 sql 查询适用于 SQLite 而不适用于 postgresql

use*_*065 5 sqlite postgresql ruby-on-rails

以下查询适用于本地但不适用于生产:(生产是 heroku 正在运行 postgreSQL,而在本地我正在运行 sqllite 数据库)

红宝石

Tutor.joins(:expertises).where(:expertises => {:subject_id => [2,4]}).group("tutors.id").having("COUNT(*) = 2")
Run Code Online (Sandbox Code Playgroud)

SQL

SELECT "tutors".* FROM "tutors" INNER JOIN "expertises" ON "expertises"."tutor_id" = "tutors"."id" WHERE ("expertises"."subject_id" IN (9)) GROUP BY tutors.id HAVING COUNT(*) = 1 ORDER BY rank DESC)
Run Code Online (Sandbox Code Playgroud)

我在生产 ActiveRecord::StatementInvalid (PGError: ERROR: column "tutors.fname" must出现在 GROUP BY 子句中或在聚合函数中使用时收到以下错误

我的表中有以下值

id                 :integer         not null, primary key
fname              :string(255)
lname              :string(255)
school             :string(255)
major              :string(255)
year               :string(255)
bio                :text
vid                :string(255)
price              :integer
phone              :string(255)
skype              :string(255)
address            :text
Run Code Online (Sandbox Code Playgroud)

当我尝试将查询调整为按所有属性分组时,出现另一个错误:

红宝石

>> Tutor.joins(:expertises).where(:expertises => {:subject_id => [2,4]}).group("tutors.*").having("COUNT(*) = 2")
Run Code Online (Sandbox Code Playgroud)

SQL

SELECT "tutors".* FROM "tutors" INNER JOIN "expertises" ON "expertises"."tutor_id" =    "tutors"."id" WHERE ("expertises"."subject_id" IN (2, 4)) GROUP BY tutors.* HAVING COUNT(*)    = 2 ORDER BY rank DESC
Run Code Online (Sandbox Code Playgroud)

ActiveRecord::StatementInvalid: PGError: ERROR: 无法识别类型导师的排序运算符提示:使用显式排序运算符或修改查询。

帮助!

Qua*_*noi 5

PostgreSQL不支持GROUP BY查询中未聚合和未分组的表达式。

用这个:

SELECT  t.*
FROM    (
        SELECT  tutor_id
        FROM    expertises e
        WHERE   e.subject_id IN (2, 4)
        GROUP BY
                tutor_id
        HAVING  COUNT(*) = 2
        ) e
JOIN    tutor t
ON      t.id = e.tutor_id
Run Code Online (Sandbox Code Playgroud)

这是跨平台的。


Pet*_*aut 3

嗯,不错的尝试,但是星号扩展在子句中不起作用GROUP BY。您需要实际列出所有列。或者在几个月内升级到 PostgreSQL 9.1。