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

妖精的绣舞 提交于 2019-12-12 01:27:54

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/41303379/how-can-i-sort-the-result-of-a-query-based-on-the-one-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!