简体   繁体   中英

How to make SQL search query for firstname, lastname

If I have for example an model:

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

And an input field where you can search for an .The different search queries could be:

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

Which search query in SQL would be the best? Actually I could imagine this search query:

  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

error: 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

Problem: Finds nothing!

Yes, you have to search it on both first name and last name like this

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

but if the data is too big. You can use the full text search engines like Solr or thinkin sphinx

To make search on firstname, lastname and fullname;

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

It works!

Yes, if you want search on lastname and firstname you must do :

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

An another solution : https://github.com/ernie/squeel , https://github.com/ernie/squeel#predicates

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM