如何在ORDER BY子句中定义自定义订单? [英] How to define a custom order in ORDER BY clause?
本文介绍了如何在ORDER BY子句中定义自定义订单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下查询:
SELECT *
FROM articles
WHERE article.category IN (1, 57, 67, 78)
ORDER BY article.category ASC
我不想按升序排序,而是想像这样:
Instead of ordering it ascending, I would like to order it like:
ORDER BY article.category (1, 67, 78, 57)
这可能吗?
推荐答案
使用FIELD函数:-
Use the FIELD function:-
SELECT *
FROM articles
WHERE article.category IN (1, 57, 67, 78)
ORDER BY FIELD(article.category, 1, 67, 78, 57)
编辑-如果找不到,它将返回0,因此,如果要先对2个值进行排序,则函数中可能只包含这2个值,但取反并按降序排序.
EDIT - If not found it will return 0, so if you want 2 values sorted first then possibly just have those 2 in the function but reversed and sort descending.
SELECT *
FROM articles
WHERE article.category IN (1, 57, 67, 78)
ORDER BY FIELD(article.category, 67, 1) DESC
这将把类别1放在第一位,其次是类别67,然后再加上其他任何类别
This will put category of 1 first, category 67 afterwards, followed by any others
这篇关于如何在ORDER BY子句中定义自定义订单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文