Groups
Groups
Sign in
Groups
Groups
Ruby on Rails Taiwan
Conversations
About
Send feedback
Help
Model內隨機取出資料:正解
9 views
Skip to first unread message
JellyCatz果凍喵
unread,
Jul 8, 2008, 10:28:17 PM
7/8/08
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to Ruby on Rails Taiwan
話說...之前有個KFC小鬼寫了一個東西,我就乖乖用下去了...後來資料成長...開始找效能瓶頸...然後追到之前的語法...重新看了一次之
後...
Σ囧" 這東西是啥咪鬼!!
[Book Model]
def self.find(*args)
if args.first.to_s == "random"
ids = connection.select_all("SELECT id FROM books")
super(ids[rand(ids.length)]["id"].to_i)
else
super
end
end
簡單的來說就是自寫SQL...把整個Book Model的"全部的id"都select出來...存在記憶體成為array後...然後再
random......
(小鬼...你接到的case都太幸福了...BigO = N...)
後來找了些東西...改成
[Book Model]
def self.find(*args)
if args.first.to_s == "random"
super(find(:first , :offset => (count * rand).to_i))
else
super
end
end
(瞬間BigO = 1...)
簡單的來說就是取出count後rand取得數後用offset位移的方式,而要不同的數量就開一個map,跑多次丟進去就可以取得該數量的不同資料
(map特性為資料不為重複:P,判斷為map.count[未查,應該是]),而上面兩例都可以使用Book.find("random")取得單一
個隨機資料
JellyCatz果凍喵
unread,
Jul 19, 2008, 7:07:49 AM
7/19/08
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to Ruby on Rails Taiwan
自補充
之前和朋友大概聊過condition的問題...很明顯最佳解並無法使用在有condition的狀況,所以這時候就要牽涉到碰撞機率的問題
也就是寫一個程式判斷取出的東西是否符合自己想要的,不是的話就重取
至於碰撞率低而資料量又大...可以考慮維護另外一個random table,也就是增修刪查資料時另外維護該表索引index(符合random的
資料),之後在該表random後反查即可
當然還有很多解法,高級點得DB可以用DB view的解法...那這邊就在我自己涉獵範圍以外了 :P 有其他好的方法歡迎討論&提出的
Reply all
Reply to author
Forward
0 new messages