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: 无法识别类型导师的排序运算符提示:使用显式排序运算符或修改查询。
帮助!
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)
这是跨平台的。
| 归档时间: |
|
| 查看次数: |
1246 次 |
| 最近记录: |