2012-07-30 89 views
2

我想識別和計算具有特定數量的消息和post.location不是零的帖子。紅寶石複雜計數

我有大約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" 

回答

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 。 (我是從記憶中寫下來的,所以你可能不得不在某些地方調整它,但總的想法應該可行)。

+0

這看起來不錯,我如何驗證post.location不是零? – PEF 2012-07-30 09:24:32

+0

我剛更新了答案.. – Tigraine 2012-07-30 11:38:03

1

您可以在您發佈模型中使用此範圍

範圍:give_a_valid_name,拉姆達{| N | (「messages」).having(「COUNT(messages.id)=#{n}」)。其中(「location IS NOT NULL」)}

然後使用Post.give_a_valid_name(5).size來獲取有5條消息的帖子數量。

希望這會有所幫助。

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")語法。