我真的很难弄清楚如何在活动记录的区域中执行这个查询和其他类似的查询。
select users.id,
users.name,
maps.count as map_count,
from users
left join (select user_id, count(map_id) as count from maps_users group by user_id) maps on users.id = maps.user_id
从表面上看,它看起来就像Nik的例子(http://magicscalingsprinkles.wordpress.com/2010/01/28/why-i-wrote-arel/):
photo_counts = photos.
group(photos[:user_id]).
project(photos[:user_id], photos[:id].count)
users.join(photo_counts).on(users[:id].eq(photo_counts[:user_id]))
但我不能让它在rails中使用活动记录。我认为等效项应该是这样的,但它出错了:(
maps = Map.arel_table
map_counts = Map.group(maps[:owner_id]).
select(maps[:owner_id]).
select(maps[:id].count.as("map_count"))
users = User.joins(map_counts).on(User.arel_table[:id].eq(map_counts[:map_count]))
你有什么建议吗?
发布于 2011-06-15 15:05:35
首先用project替换select。在关系代数中,SELECT (限制)是WHERE子句。
其次,你可以进行二次选择。
sub_restriction = b.
where( b[:domain].eq(1) ).
project( b[:domain] )
restriction = a.
where( a[:domain].in sub_restriction )
“子选择”完成!:-)
发布于 2011-03-18 14:26:11
是啊,那篇文章也让我很想学习Arel魔法。
Stackoverflow上所有的“使用Arel做一些智能的事情”的问题都是用SQL来回答的。从文章和研究来看,我可以说Arel不是ActiveRecord。尽管查询是动态制定的,但Active没有能力映射完全形成的Arel投影的结果。
您可以使用指定运算符
https://github.com/activerecord-hackery/squeel
但是没有子选择。
更新:天哪,我5年前就回答了这个问题。不是开玩笑,链接已经死了:)
https://stackoverflow.com/questions/5178799
复制相似问题