我一直在将一些MySQL查询迁移到PostgreSQL来使用Heroku。我的大部分的查询做工精细,但我一直有类似的重复错误,当我通过使用组:PostgreSQL GROUP BY与MySQL不同?
ERROR: column "XYZ" must appear in the GROUP BY clause or be used in an aggregate function
有人能告诉我什么,我做错了什么?
的MySQL其中工程100%:
SELECT `availables`.*
FROM `availables`
INNER JOIN `rooms` ON `rooms`.id = `availables`.room_id
WHERE (rooms.hotel_id = 5056 AND availables.bookdate BETWEEN '2009-11-22' AND '2009-11-24')
GROUP BY availables.bookdate
ORDER BY availables.updated_at
PostgreSQL的错误:
ActiveRecord::StatementInvalid: PGError: ERROR: column "availables.id" must appear in the GROUP BY clause or be used in an aggregate function:
SELECT "availables".* FROM "availables" INNER JOIN "rooms" ON "rooms".id = "availables".room_id WHERE (rooms.hotel_id = 5056 AND availables.bookdate BETWEEN E'2009-10-21' AND E'2009-10-23') GROUP BY availables.bookdate ORDER BY availables.updated_at
Ruby代码生成SQL:
expiration = Available.find(:all,
:joins => [ :room ],
:conditions => [ "rooms.hotel_id = ? AND availables.bookdate BETWEEN ? AND ?", hostel_id, date.to_s, (date+days-1).to_s ],
:group => 'availables.bookdate',
:order => 'availables.updated_at')
的预期输出(从工作MySQL查询):
+-----+-------+-------+------------+---------+---------------+---------------+ | id | price | spots | bookdate | room_id | created_at | updated_at | +-----+-------+-------+------------+---------+---------------+---------------+ | 414 | 38.0 | 1 | 2009-11-22 | 1762 | 2009-11-20... | 2009-11-20... | | 415 | 38.0 | 1 | 2009-11-23 | 1762 | 2009-11-20... | 2009-11-20... | | 416 | 38.0 | 2 | 2009-11-24 | 1762 | 2009-11-20... | 2009-11-20... | +-----+-------+-------+------------+---------+---------------+---------------+ 3 rows in set
sooo ...我会更好地使用bookdate上的独特功能吗?如果我这样做了,我是否仍然需要group by子句? – holden 2009-11-20 10:07:35
'DISTINCT'比'GROUP BY'慢。所以你应该小心,如果可能的话,更喜欢'GROUP BY'解决方案。 – Franz 2009-11-20 11:10:08