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
Solution 1:
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 with the same condition as the IF() statementWHERE 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
Solution 2:
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.
Post a Comment for "How Can I Sort The Result Of A Query Based On The One Column?"