Skip to content

Instantly share code, notes, and snippets.

@nihaokid
Created June 12, 2017 15:09
Show Gist options
  • Save nihaokid/3c8d11a6ded4a0503d3a26cfcfcbce34 to your computer and use it in GitHub Desktop.
Save nihaokid/3c8d11a6ded4a0503d3a26cfcfcbce34 to your computer and use it in GitHub Desktop.
mysql order by relevance or search function
/*
https://dev.mysql.com/doc/refman/5.6/en/fulltext-search.html
https://dev.mysql.com/doc/refman/5.6/en/indexes.html
https://stackoverflow.com/questions/11144394/order-sql-by-strongest-like
*/
CREATE FULLTEXT INDEX index_name
ON table_name (col1, col2, col3)
SELECT * FROM table_name
WHERE MATCH (col1,col2,col3)
AGAINST ('keyword' IN NATURAL LANGUAGE MODE);
/* https://stackoverflow.com/questions/1588710/mysql-how-to-order-by-relevance-innodb-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
*/
SELECT id, name
FROM cards
WHERE name like '%John%'
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment