How to order by conditions in MySQL?

时间:2017-09-28 08:34:27

标签: mysql sorting

It's difficult to express ... because it's not ORDER BY or ORDER BY FIELD what I'm looking for.

I have this query:

SELECT * 
FROM table 
WHERE name LIKE '%xxx%' 
OR category_name LIKE '%xxx%' 
OR description LIKE '%xxx%';

What I need is to sort results based in: - first, the ones that matches the like with "name" field - secondly, the category_name - last, the description

So I have results sorted and first the results where "xxx" was found in name.

As I told this is not ORDER BY , since that sort results based in the VALUE, not in the field matches.

1 个答案:

答案 0 :(得分:3)

您可以使用case中的order by根据您的条件对结果进行排序,例如

SELECT 
  * 
FROM
  TABLE 
WHERE (
    `name` LIKE '%xxx%' 
    OR category_name LIKE '%xxx%' 
    OR description LIKE '%xxx%'
  ) 
ORDER BY 
  CASE
    WHEN `name` LIKE '%xxx%' 
    THEN 0 
    WHEN category_name LIKE '%xxx%' 
    THEN 1 
    WHEN description LIKE '%xxx%' 
    THEN 2 
    ELSE 3 
  END ASC