2013-05-08 108 views
-1

我在mysql數據庫的列letters中有以下數據。我將它們保存在varchar中:數據庫中的字符串數組。匹配並返回值

letters 
["a","b"] 
["a","b","d"] 
["a","d"] 
["d","c","e"] 
["e","c","f"] 
["c","f"] 
["f","e"] 

我想匹配一些元素。當我有params[:lttrs]"a",我想回:

["a","b"] 
["a","b","d"] 
["a","d"] 

當我有params[:lttrs]"c,e",我想回:

["d","c","e"] 
["e","c","f"] 

我嘗試檢索所有行,然後相互匹配其中有include?('a'),但以此,我一次只能做一個元素。這是方法嗎?

+1

當'params [:lttrs]'是「a,c,e」還是「b,d,e,f」會發生什麼? – 2013-05-08 07:12:16

回答

0

您可以使用LIKE運算符進行通配符匹配。這個解決方案比使用ruby更快。但如果你有一個大桌子,它會很慢。如果您提供關於數據設計原因的更多詳細信息,我們將能夠提出其他方法。

like_params = params[:lttrs].split(",").map{|letter| "%#{letter}%"} 
like = like_params.map{ "LIKE ?"}.join(" OR ") 
Model.where(like, like_params) 
0

你可以嘗試做這樣的事情:

query = "letters " 
r = 1 
letters_arr = params[:lttrs].split(",") 
letters_arr.each do |l| 
    if r == 1: 
    query << " like '%#{l}%'" 
    else 
    query << " or like '%#{l}%'" 
    end 
end 

letters_found = WhateverModel.where(查詢)

顯然,你需要確保的是,在PARAMS比這更安全地處理,但這應該會讓你走上正軌。

相關問題