使用 Arel 的嵌套查询 (Rails3)

发布于 2024-10-01 07:14:43 字数 271 浏览 4 评论 0原文

例如,我有 2 个模型:

购买 (belongs_to :users) 用户 (has_many :purchases)

我想选择至少进行过一次购买的所有用户。

在 SQL 中我会这样写:

SELECT * FROM `users` WHERE `id` IN (SELECT DISTINCT `buyer_id` FROM  `purchases`)

还有一个问题:是否有任何完整的文档或书籍介绍 Arel?

For example, I have 2 models:

Purchase (belongs_to :users)
User (has_many :purchases)

I want to select all users that have at least one purchase.

In SQL I would write like this:

SELECT * FROM `users` WHERE `id` IN (SELECT DISTINCT `buyer_id` FROM  `purchases`)

And one more question: are there any full documentation or book that cover Arel?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

池予 2024-10-08 07:14:43

嗯,我想回答我的问题......:)

buyers=purchases.project(:buyer_id).group(purchases[:buyer_id]) #<-- all buyers
busers=users.where(users[:id].in(buyers))  #<--answer

Hmm, I'd like to answer my question... :)

buyers=purchases.project(:buyer_id).group(purchases[:buyer_id]) #<-- all buyers
busers=users.where(users[:id].in(buyers))  #<--answer
烟燃烟灭 2024-10-08 07:14:43

Rails Guide 有非常好的 ARel 文档。

http://guides.rubyonrails.org/active_record_querying.html#conditions

Rails API 是对于一些比较晦涩的选项也非常有用。我只是用“rails api”搜索一个特定术语,它首先出现。

The Rails Guide has really good documentation for ARel.

http://guides.rubyonrails.org/active_record_querying.html#conditions

The Rails API is also pretty useful for some of the more obscure options. I just google a specific term with "rails api" and it comes up first.

败给现实 2024-10-08 07:14:43

我不相信上面的代码会发出嵌套查询。相反,它似乎会发出 2 个单独的 SQL 查询。您可能具有相当的速度(取决于您对性能的关注程度),但由于到服务器有 2 次往返,它无法提供与嵌套查询相同的优势。

I don't believe that the code above issues a nested query. Instead, it appears that it would issue 2 separate SQL queries. You may have comparable speed (depending on how concerned you are with performance), but with 2 round trips to the server, it doesn't offer the same benefits of nested queries.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文