带子句的复杂 ORDER BY

complex ORDER BY with clauses

我在尝试对 MySQL 查询的结果进行排序时遇到问题。

table包含用户信息,特别是:

ORDER BY 子句应将用户分为 6 个主要组,并在每个组内按 last_login DESC 对他们进行排序。

因此我试图得到(伪代码):

first show users: user_status = 1 AND user_verified = true, last_login DESC
then: user_status = 1 AND user_verified = false, last_login DESC
then: user_status = 2 AND user_verified = true, last_login DESC
then: user_status = 2 AND user_verified = false, last_login DESC
then: user_status = 0 AND user_verified = true, last_login DESC
then: user_status = 0 AND user_verified = false, last_login DESC

我在将其组合成一个连贯的 ORDER BY 子句时遇到问题,如有任何帮助,我们将不胜感激!

您可以在 ORDER BY 子句中使用布尔表达式,因为它们对于 true 的计算结果为 1 或对于 false 的计算结果为 0

在您的情况下,您可以将要求简化为:

ORDER BY user_status = 1 DESC,
         user_status = 2 DESC,
         user_status = 0 DESC,
         user_verified DESC,
         last_login DESC;

或:

ORDER BY CASE user_status 
           WHEN 1 THEN 1
           WHEN 2 THEN 2
           WHEN 0 THEN 3
         END,
         user_verified DESC,
         last_login DESC;

或使用FIELD()函数:

ORDER BY FIELD(user_status, 1, 2, 0),
         user_verified DESC,
         last_login DESC;