简体   繁体   English

使用sql搜索多个字段的功能

[英]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:如果只使用一个字段,让我们说Name ,我必须使用它作为我的搜索键,那么我可以简单地做这样的事情:

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

and get the data for user 1.并获取用户 1 的数据。

If I want the search operation to take into account other fields too, lets say Surname , I am not sure how to proceed.如果我希望搜索操作也考虑其他字段,比如说Surname ,我不知道如何继续。

How would order by know what column to use in the end so I can return the list based on relevance.如何order by知道最终使用哪个列来order by以便我可以根据相关性返回列表。

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.您可以做的是按每行中所有感兴趣的列的最小difference排序。

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 .在此处尝试交互式小提琴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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