使用 Arel 的嵌套查询 (Rails3)
例如,我有 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
嗯,我想回答我的问题......:)
Hmm, I'd like to answer my question... :)
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.
我不相信上面的代码会发出嵌套查询。相反,它似乎会发出 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.