简体   繁体   中英

MySQL - Search/SELECT which is ordered by relevance?

I have a table setup as follows:

userid year  model  color  transmission  interiorcolor wheels
-------------------------------------------------------------------
   1   2005  Fiesta   Red   MT             Black        Stock
   2   2008  Monaro   Red   AT             Black        Stock
   3   2005  F-150S   Blue   AT            Black + Red  Stock
   4   2008  Fiesta   Green   MT           Black        Stock

Now I am building an SQL search (no standard build in full text search), and I want to results to be somewhat relevant.

What i mean is that for example if someone types in "2008 Fiesta", right now with a basic query the results come out in this order

id #1, id #2, id #4

But really I would like #4 to be on the top of the search in that case because it matches my search on two fields instead of just one field.

Thank you!

You may want to take a look at using Lucene (or SOLR on top of Lucene), instead of relying on MySQL for something like this. You can still store your real data in MySQL. The general setup I use is SOLR/Lucene to do full text/relevance searches to get the ids of the entities I'm interested in, then hit MySQL to grab the actual data for those entities. Using SOLR/Lucene gives you a full text search and adds a lot more power in the ways you can search/order the data, plus it gives things like stemming and the like.

I think your select statement is like:

LIKE %2008 Fiesta%

Try taking the last % , it will work

This is crude but it should work for you:

SELECT id, SUM(Relevance) as SearchRelevance
FROM(
SELECT id, 1 as Relevance
FROM cars
WHERE year = 2008
UNION ALL
SELECT id, 1 as Relevance
FROM cars
WHERE model='Fiesta') AS t
GROUP BY id
ORDER BY SUM(Relevance) DESC

Basically it has a search for each criteria, UNIONs them all together and then groups them and orders by the SUM of relevance (where you get one point per matching item).

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