Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - How to ORDER BY RELEVANCE? INNODB Table

I've got about 20,000 rows in an INNODB table called 'cards', so FULLTEXT is not an option.

Please consider this table:

id     |     name     |     description ---------------------------------------------------------- 1        John Smith       Just some dude 2        Ted Johnson      Another dude 3        Johnathan Todd   This guy too 4        Susan Smith      Her too 5        Sam John Bond    And him 6        John Smith       Same guy as num 1, another record 7        John Adams       Last guy, promise 

So, say the user searches for 'John', I want the result set to be in the order of:

7        John Adams 6        John Smith 3        Johnathan Todd 5        Sam John Bond 2        Ted Johnson 

Please note that we've only pulled 'John Smith' once, we took his most recent entry. Due to my data, all names are for the same exact person, no need to worry about 2 different guys named John Smith. Ideas? Let me know if I can clarify anything.

like image 253
k00k Avatar asked Oct 19 '09 13:10

k00k


People also ask

How do I get descending order in MySQL?

The MySQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

Does MySQL use index for order by?

Use of Indexes to Satisfy ORDER BY. In some cases, MySQL may use an index to satisfy an ORDER BY clause and avoid the extra sorting involved in performing a filesort operation.

How do I sort alphabetically in MySQL?

Use the ASC option to sort the result set in ascending order and the DESC option to sort the result set in descending order.

Which is the default ordering if order by is not provided?

By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.


1 Answers

version 1:

SELECT max(id) id, name   FROM cards  WHERE name like '%John%'  GROUP BY name  ORDER BY CASE WHEN name like 'John %' THEN 0                WHEN name like 'John%' THEN 1                WHEN name like '% John%' THEN 2                ELSE 3           END, name 

version 2:

SELECT max(id) id, name   FROM cards  WHERE name like '%John%'  GROUP BY name  ORDER BY CASE WHEN name like 'John%' THEN 0                WHEN name like '% %John% %' THEN 1                WHEN name like '%John' THEN 2                ELSE 3           END, name 
like image 101
manji Avatar answered Sep 30 '22 14:09

manji