如何对firstname,lastname进行sql搜索查询

时间:2013-09-18 09:54:45

标签: sql ruby-on-rails ruby-on-rails-3

如果我有一个模型:

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 个答案:

答案 0 :(得分: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

这样的全文搜索引擎

答案 1 :(得分:0)

搜索firstname,lastname和fullname;

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

有效!

答案 2 :(得分:-1)

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

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

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

答案 3 :(得分:-1)

User.where("(first_name || ' ' || last_name) like :q", :q => params[:search])