4

例如,如果我有一个模型:

User :firstname   :lastname
     joseph       smith
     anna         bauer
     ...          ...

还有一个输入字段,您可以在其中搜索用户。不同的搜索查询可能是:

  searchquery1:  smith joseph
  searchquery2:  joseph smith
  searchquery3:  joseph
  searchquery4:  smith

SQL 中的哪个搜索查询最好?其实我可以想象这个搜索查询:

  where 'firstname OR lastname  LIKE ?', "%#{search}"

第一次尝试:

def self.search(search)
 if search
   select('CONCAT(vorname, " ", nachname) as full_name, *')
   where ['vorname LIKE :s OR nachname  LIKE :s OR full_name LIKE :s', :s => "%#{search}"]
 else
  scoped
 end
end

错误:SQLite3::SQLException: no such column: full_name

第二次尝试:

def self.search(search)
 if search
  a = search.split
   where('firstname OR lastname  LIKE ?', a[1])
   where('firstname OR lastname  LIKE ?', a[2]) unless a[2].nil?
  else
  scoped
 end
end

问题:什么也没找到!

4

4 回答 4

5

是的,您必须像这样搜索名字和姓氏

select('(firstname || " " || lastname) as \'full_name\', *')
where ['firstname LIKE :s OR lastname  LIKE :s OR full_name LIKE :s', :s => "%#{search}"]

但如果数据太大。您可以使用 Solr 或 thinkin sphinx 等全文搜索引擎

于 2013-09-18T10:04:55.787 回答
0

搜索名字、姓氏和全名;

Member.where ['first_name LIKE :s OR last_name LIKE :s OR CONCAT(first_name,last_name) LIKE :s', :s => "#{search.delete(' ')}"]

有用!

于 2016-06-16T04:18:20.887 回答
-1

是的,如果您想搜索姓氏和名字,您必须这样做:

User.where('firstname or lastname like ?', params[:search])

另一种解决方案:https ://github.com/ernie/squeel,https : //github.com/ernie/squeel#predicates

于 2013-09-18T10:03:44.550 回答
-1
User.where("(first_name || ' ' || last_name) like :q", :q => params[:search])
于 2016-05-07T04:44:21.830 回答