Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql: Order by like?

assume that we are performing search using keywords: keyword1, keyword2, keyword3

there are records in database with column "name":

 1: John Doe 2: Samuel Doe 3: John Smith 4: Anna Smith 

now Query:

SELECT * FROM users WHERE (name LIKE "%John%" OR name LIKE "%Doe%") 

it will select records: 1,2,3 (in this order) but i want to order it by keyword in example keyword1=John, keyword2=Doe so it should be listed by keywords: 1,3,2 (because i want to perform search for "Doe" after searching for "John")

I was thinking about SELECT DISTINCT FROM (...... UNION .....) but it will be much easier to order it somehow in another way (real query is really long)

are there any tricks to create such order?

like image 476
dfens Avatar asked Aug 31 '10 12:08

dfens


People also ask

Can we use like with ORDER BY?

When you use LIKE operator to search and fetch the matched results from the database, the records are selected based on their entry. On another hand, the ORDER BY keyword allows you to sort the result-set in ascending or descending order based on a specific column.

How do I sort in MySQL?

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.

How do I change the order of rows in MySQL?

An "ALTER TABLE ORDER BY" statement exist in the syntaxes accepted by MySQL. According to the documentation, this syntax: - only accept *one* column, as in "ALTER TABLE t ORDER BY col;" - is used to reorder physically the rows in a table, for optimizations.

How do I show ascending order in MySQL?

You can use the keyword ASC or DESC to get result in ascending or descending order. By default, it's the ascending order.


1 Answers

order by case      when name LIKE "%John%" then 1      when name LIKE "%Doe%"  then 2      else 3  end 
like image 78
D'Arcy Rittich Avatar answered Sep 19 '22 06:09

D'Arcy Rittich