Rails ActiveRecord基于单词包含但不包含部分单词查询字段

时间:2018-01-17 15:28:51

标签: ruby-on-rails activerecord sql-like

我知道我们有LIKE选项来搜索部分单词,精确单词匹配以及单词包含(但有一些问题,请在下面解释一下)

 User.where("name like ?", "%john%")  
 # above code will search the name column and it will return records even if it 
   matches the character partially i.e "joh" also return a record.

 User.where("name like ?", "john")
 # above code will return a record if 'john' word is in the name column. 
   It will match the exact word.

 User.where("name like ?", "% john %")
 # this will return a record if name column contains 'john' text i.e "Sample john victor".
   But if a record has "John victor" then it won't find this record because '% john %' 
   can only match middle of the words except first and last word in the name column 
   since we having space in both front and end of the word in our search i.e "% john %"

有人可以帮我在表中的一列字符串中找到基于单词contains的记录吗?

1 个答案:

答案 0 :(得分:0)

您没有指定您正在使用的数据库,并且可能的不同数据库允许不同形式的匹配。例如。在postgres中你可以使用SIMILAR TO

对于一个直接的SQL LIKE,我认为你需要在OR一起做几个选项。

E.g。

User.where("(name = ?) or (name like ?) or (name like ?) or (name like ?))", 
         'john'
         '% john %', 
         'john %', 
         '% john')

这将获得约翰'的价值观,其中包括约翰'以#john'开头。以及#john'分别

这可能会非常慢,具体取决于您查询的数据,但我认为它可以达到您想要的效果。