Reputation: 337
I have this table, where I am searching for records based on name, description, category_name. What I want the order of records to be:
Results that matched with name or part of the name,
Then Results that matched with the description as well as category_name,
Results that matched with the only category_name,
Results that matched with the description
Please see that I am trying to order the records based on their match. Simple order by name with sorting them all according to name.
Sample Data:
name,description,category_name
abc,xyz_usama, asz
usama,this is description,person
abc, xyz, usama
jhon,this is usama,person usama
now if I searched using keyword usama: result should be:
2 ( matched with name )
4 ( description + category )
3 ( category )
1 ( description )
Upvotes: 0
Views: 64
Reputation: 1270391
You can use a case
expression`. Your question is not really clear on what the data looks like, but the idea is:
order by (case when name like '%' || :search || '%'
then 1
when category_name like '%' || :search || '%' and
description like '%' || :search || '%'
then 2
when category_name like '%' || :search || '%'
then 3
when description like '%' || :search || '%'
then 4
else 5
end)
Upvotes: 1
Reputation: 42728
ORDER BY
/* Results that matched with name or part of the name, */
name LIKE 'name_pattern' DESC,
/* Then Results that matched with the description as well as category_name, */
/* Results that matched with the only category_name, */
category_name LIKE `category_name_pattern` DESC,
description LIKE `description_pattern` DESC
/* Results that matched with the description */
/* i.e. all another records */
If all pattern are the same substring you may use simple
ORDER BY LOCATE('pattern', CONCAT(name, category_name, description))
Upvotes: 1