Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order mysql results by column priority?

Tags:

mysql

How to order mysql results by column priority?

Example. I have a table of products, the table contains two columns, product name (p.name) and product description (p.desc).

Users should be able to enter keywords to find products in the database.

"p.name LIKE '%keyword%' OR p.desc LIKE '%keyword%'

I want the results that match p.name returned first and the p.desc second.

How would I go about achieving this?

like image 634
payling Avatar asked Jan 28 '11 13:01

payling


2 Answers

I would try something like

ORDER BY (NOT (p.name LIKE '%keyword%'))

If your first condition is satisfied, order by clause will evaluate to false. Thus, such records will be pushed ahead.

edit
Equals sign (=) has probably got into the question by mistake.

like image 52
Nikita Rybak Avatar answered Oct 14 '22 15:10

Nikita Rybak


You should try MySQL Full Text Search as in MATCH() ... AGAINST and more here. Then order by the search rank with the columns.

like image 39
shamittomar Avatar answered Oct 14 '22 16:10

shamittomar