简体   繁体   中英

Search functionality for multiple fields using sql

I have a table that holds user data. It looks something like this:

ID Name  Surname Age
1  Alice Moore   23
2  David Moore   45

If working with only one field, lets say Name , which I have to use for my search key then I could simply do something like this:

Select * from Users where Name Like '% Al %'
ORDER BY DIFFERENCE(Name , 'Al') desc;

and get the data for user 1.

If I want the search operation to take into account other fields too, lets say Surname , I am not sure how to proceed.

How would order by know what column to use in the end so I can return the list based on relevance.

Before anything I'd like to say that I'm not sure how advisable it would be following my solution below in tables with a considerable amount of data. It's simply something I came up that I think should work for your case.

First try

What you could do is order by the minimum difference of all columns of interest in each row.

SELECT FirstName, 
       LastName, 
(SELECT MIN(v) 
   FROM (VALUES (DIFFERENCE(FirstName , 'Al')), 
                (DIFFERENCE(LastName , 'Al'))) AS value(v)) as diff

FROM Users WHERE FirstName LIKE 'Al%' OR FirstName LIKE 'Al%'
ORDER BY diff DESC;

Try an interactive fiddle here .

Second try

Another option is ordering your result in a descending order of the difference of the concatenated string of all the rows of interest.

SELECT FirstName, 
       LastName 
FROM   Users 
WHERE  CONCAT (FirstName, LastName) LIKE 'Al%'
ORDER BY 
       DIFFERENCE(CONCAT (FirstName, LastName) , 'Al') DESC;

Try an interactive fiddle here .

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