stack
stack

Reputation: 10218

How can I sort the result of a query based on the one column?

Here is my query:

SELECT name, usage_guidance, total_used_num
FROM tags
WHERE
( name LIKE CONCAT('%', ?, '%') OR
  usage_guidance LIKE CONCAT(?, '%') ) AND
name NOT IN ($in)
LIMIT 6

Now I want to order the result by name column .. I mean I want to put the matched results because of name LIKE CONCAT('%', ?, '%') condition in first, and then other results should be after them. How can I do that?

Upvotes: 0

Views: 155

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269503

You would add the where conditions to the order by clause:

order by (name like CONCAT('%', ?, '%')) desc,
         (usage_guidance LIKE CONCAT(?, '%')) desc

MySQL treats boolean expressions in a numeric context as numbers, with "1" for true and "0" for false. Hence the desc order for the sorts.

Note that the second condition on usage_guidance is not strictly necessary to answer the question.

Upvotes: 0

zeb
zeb

Reputation: 99

If I understand your question correctly, you want the results where name LIKE %SOMETHING% is matched displayed first.

You could achieve this by setting an additional select field in an IF() statement with the same condition as the WHERE clause for name and sort by that field:

SELECT name, usage_guidance, total_used_num, name LIKE CONCAT('%', ? , '%') as sort_field
FROM tags
WHERE
( name LIKE CONCAT('%', ?, '%') OR
  usage_guidance LIKE CONCAT(?, '%') ) AND
name NOT IN ($in)
ORDER BY sort_field DESC
LIMIT 6

Edit: I just realized, you don't need the IF() statement at all

Upvotes: 1

Related Questions