我想识别并计算具有特定数量的邮件和post.location不是nil的帖子。
我有大约100k行,它用于统计用途,所以我需要快速查询(顺便说一句,我可能需要索引post.location)。
我怎样才能以最简单,最快捷的方式做到这一点?
这是我的架构:
create_table "posts", :force => true do |t|
t.string "ref"
t.string "title"
t.string "author"
t.datetime "created_at"
t.datetime "updated_at"
t.string "location"
t.float "lat"
t.float "long"
end
create_table "messages", :force => true do |t|
t.integer "post_id"
t.integer "status_id"
t.integer "user_id"
t.string "content"
t.datetime "created_at"
t.datetime "updated_at"
t.float "lat"
t.float "long"
end
add_index "messages", ["post_id"], :name => "index_messages_on_post_id"
add_index "messages", ["created_at"], :name => "index_messages_on_created_at"
答案 0 :(得分:3)
您正在寻找的SQL查询应该看起来像这样:
SELECT COUNT(posts.id)
FROM posts
JOIN messages ON (posts.id = messages.post_id)
GROUP BY (posts.id) HAVING (count(messages.id) > ?)
WHERE posts.location IS NOT NULL
然后,您可以将其转换为ActiveRecord查询或仅使用find_by_sql
。
(我是从记忆中写的,所以你可能不得不在某些地方调整它......但总体思路应该有效。)
答案 1 :(得分:1)
您可以在Post模型中使用此范围
范围:give_a_valid_name,lambda {| n | joins(:messages).having(“COUNT(messages.id)=#{n}”)。where(“location IS NOT NULL”)}
然后使用Post.give_a_valid_name(5).size获取包含5条消息的帖子数。
希望这有帮助。
答案 2 :(得分:0)
好的,由于Tigraine和az7ar的答案,我设法完成了它。这是有用的:
Post.joins(:messages).select('post_id as id').group("post_id").having("count(*) = 1").where('location IS NOT NULL')
感谢Tigraine提供JOIN建议,感谢az7ar提供.where("location IS NOT NULL")
语法。