如何获取activerecord中的活跃流派?
我正在使用 Rails 3 和 postgresql。我有以下流派:摇滚、氛围、另类、浩室。
我还注册了两个用户。一个有摇滚,另一个有浩室,作为他们的流派。我需要归还摇滚和浩室风格的对象。
我找到了两种方法来做到这一点。一种是使用 group:
Genre.group('genres.id, genres.name, genres.cached_slug, genres.created_at, genres.updated_at').joins(:user).all
另一种是使用 DISTINCT:
Genre.select('DISTINCT(genres.name), genres.cached_slug').joins(:user)
两者都返回相同的所需结果。但哪一种性能更好呢?使用 group() 看起来很混乱,因为我必须指示 Genre 表中的所有字段,否则我会收到如下错误:
ActiveRecord::StatementInvalid: PGError: ERROR: column "genres.id" must appear in the GROUP BY clause or be used in an aggregate function
: SELECT genres.id FROM "genres" INNER JOIN "users" ON "users"."genre_id" = "genres"."id" GROUP BY genres.name
I am using Rails 3 and postgresql. I have the following genres: rock, ambience, alternative, house.
I also have two users registered. One has rock and the other house, as their genres. I need to return rock and house genre objects.
I found two ways to do this. One is using group:
Genre.group('genres.id, genres.name, genres.cached_slug, genres.created_at, genres.updated_at').joins(:user).all
And the other using DISTINCT:
Genre.select('DISTINCT(genres.name), genres.cached_slug').joins(:user)
Both return the same desired results. But which one is better performance wise? Using group() looks messy since I have to indicate all the fields in the Genre table otherwise I'll get errors as such:
ActiveRecord::StatementInvalid: PGError: ERROR: column "genres.id" must appear in the GROUP BY clause or be used in an aggregate function
: SELECT genres.id FROM "genres" INNER JOIN "users" ON "users"."genre_id" = "genres"."id" GROUP BY genres.name
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
DISTINCT
和GROUP BY
通常会生成相同的查询计划,因此两种查询结构的性能应该相同。由于您没有使用任何聚合函数,因此您应该使用在您的情况下最有意义的函数,我相信就是这个:
稍后尝试阅读代码并记住您在这里做了什么时,这会更清楚正如您所指出的,不那么混乱。
更新
这取决于您使用的 Postgresql 版本。使用版本< 8.4,
GROUP BY
更快。对于 8.4 及更高版本,它们是相同的。A
DISTINCT
andGROUP BY
usually generate the same query plan, so performance should be the same across both query constructs.Since you're not using any aggregate functions, you should use the one that makes the most sense in your situation, which I believe is this one:
This will be more clear when trying to read your code later and remember what you did here and, as you pointed out, is much less messy.
Update
It depends on the version of Postgresql you are using. Using versions < 8.4,
GROUP BY
is faster. With version 8.4 and later, they are the same.