SQL Select Like Keywords in Any Order

岁酱吖の 提交于 2019-12-13 12:33:32

问题


I am building a Search function for a shopping cart site, which queries a SQL Server database. When the user enters "Hula Hoops" in the search box, I want results for all records containing both "Hula" and "Hoop", in any order. Furthermore, I need to search multiple columns (i.e. ProductName, Description, ShortName, MaufacturerName, etc.)

All of these product names should be returned, when searching for "Hula hoop":

  • Hula hoop
  • Hoop Hula
  • The Hoopity of xxhula sticks

(Bonus points if these can be ordered by relevance!)


回答1:


SQL Server Full Text Search should help you out. You will basically create indexes on the columns you want to search. in the where clause of your query you will use the CONTAINS operator and pass it your search input.

you can start HERE or HERE to learn more




回答2:


It sounds like you're really looking for full-text search, especially since you want to weight the words.

In order to use LIKE, you'll have to use multiple expressions (one per word, per column), which means dynamic SQL. I don't know which language you're using, so I can't provide an example, but you'll have to produce a statement that's like this:

For "Hula Hoops":

where (ProductName like '%hula%' or ProductName like '%hoops%')
  and (Description like '%hula%' or Description like '%hoops%')
  and (ShortName like '%hula%' or ShortName like '%hoops%')

etc.

Unfortunately, that's really the only way to do it. Using Full Text Search would allow you to reduce your criteria to one per column, but you'll still have to specify the columns explicitly.

Since you're using SQL Server, I'm going to hazard a guess that this is a C# question. You'd have to do something like this (assuming you're constructing the SqlCommand or DbCommand object yourself; if you're using an ORM, all bets are off and you probably wouldn't be asking this anyway):

SqlCommand command = new SqlCommand();
int paramCount = 0;

string searchTerms = "Hula Hoops";

string commandPrefix = @"select *

from Products";

StringBuilder whereBuilder = new StringBuilder();

foreach(string term in searchTerms.Split(' '))
{
    if(whereBuilder.Length == 0)
    {
        whereBuilder.Append(" where ");
    }
    else
    {
        whereBuilder.Append(" and ");
    }

    paramCount++;

    SqlParameter param = new SqlParameter(string.Format("param{0}",paramCount), "%" + term + "%");

    command.Parameters.Add(param);

    whereBuilder.AppendFormat("(ProductName like @param{0} or Description like @param{0} or ShortName like @param{0})",paramCount);
}

command.CommandText = commandPrefix + whereBuilder.ToString();



回答3:


You might want to check out SOLR too - if you're going to be doing this type of searching. Super cool.

http://lucene.apache.org/solr/



来源:https://stackoverflow.com/questions/4763724/sql-select-like-keywords-in-any-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!