如何使用 arel/关系代数获取不同的值
我正在尽我最大的努力来思考 arel 及其背后的关系代数,但如何表示 SELECT DISTINCT 始终让我无法理解。任何人都可以解释如何arel:
SELECT DISTINCT title FROM posts;
非常感谢!
I'm doing my best to bend my brain around arel and the relational algebra behind it, but how to represent a SELECT DISTINCT
is consistently eluding my comprehension. Can anyone explain how to arel:
SELECT DISTINCT title FROM posts;
Many thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用纯 Arel(不是 Rails/ActiveRecord)有一个“不同”方法:
奇怪的是,根据其他 Arel 方法,“不同”方法是不可链接的。
Using pure Arel (not Rails/ActiveRecord) there is a "distinct" method:
Curiously, the "distinct" method is not chainable, per the other Arel methods.
Arel 的方法是:
The Arel way to do it is:
前面的答案是Rails 方式,不是吗?不是阿雷尔的方式。
这适用于 arel 1.x:
我会我猜还有另一种“更正确”的方法可以通过 API 来做到这一点,但我还没有弄清楚。
The previous answer is the Rails way, no? Not the Arel way.
This works for arel 1.x:
I'd guess there's another "more correct" way to do this via the API but I haven't figured that out yet.
如果您使用范围来执行此操作:
If you are doing this using a scope:
Post.select('DISTINCT title')
更新 1:
在发帖时,Arel 中尚不支持此功能。如今,ActiveRecord::QueryMethods 有
uniq
方法 (http://apidock.com/rails/ActiveRecord/QueryMethods/uniq" rel="nofollow noreferrer">http:// /apidock.com/rails/ActiveRecord/QueryMethods/uniq),所以您需要:更新 2:
看起来 Arel 现在支持这种行为。 @maerics 有正确答案。如果这不是被接受的答案,我会删除它。
Post.select('DISTINCT title')
Update 1:
At the time of the post, this was not available in Arel. These days, ActiveRecord::QueryMethods has the
uniq
method (http://apidock.com/rails/ActiveRecord/QueryMethods/uniq), so you'd want:Update 2:
Looks like Arel now supports this behavior. @maerics has the correct answer. I'd delete this if it wasn't the accepted answer.
由于 AREL 在其操作中始终使用 SET,因此重复的行结果将被自动删除。只需使用正常的 Project (Phi) 操作即可。
Since AREL always uses SET in it's operation, duplicate row results will be deleted automatically. Just use a normal Project (Phi) operation.