MySQL 排序依据 在顶部显示特定数据

MySQL Order by show specific data at the top

我的 activity table 中有以下数据。我想在顶部显示那些 followup_date 从今天开始按升序排列的记录,然后是那些 followup_date 是过去日期的记录,然后是那些 followup_date 是空。

DROP TABLE IF EXISTS `activity`;
CREATE TABLE IF NOT EXISTS `activity` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `type_id` int(11) NOT NULL,
  `followup_date` date DEFAULT NULL,
  `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

--
-- Dumping data for table `activity`
--

INSERT INTO `activity` (`id`, `type_id`, `followup_date`, `created`) VALUES
(1, 1, '2022-03-22', '2022-03-24 18:51:23'),
(2, 1, '2022-03-23', '2022-03-24 18:51:23'),
(3, 1, '2022-03-24', '2022-03-24 18:51:58'),
(4, 1, '2022-03-25', '2022-03-24 18:51:58'),
(5, 1, '2022-03-26', '2022-03-24 18:52:21'),
(6, 1, '2022-03-13', '2022-03-24 18:52:21'),
(7, 1, NULL, '2022-03-24 18:54:15'),
(8, 1, NULL, '2022-03-24 18:54:15');

我尝试使用下面的查询,但无法理解如何使用 ORDER BY CASE 语句来获得下面提到的结果。

SELECT * FROM `activity` ORDER BY CASE WHEN followup_date IS NULL THEN 2 WHEN followup_date >= '2022-03-24' THEN 1 END ASC

当前输出:

预期输出

我需要在上述查询中进行哪些更改才能获得预期输出

我将表达式移到 select-list 中以便我们可以在结果中看到它,但您可以将其保留在 ORDER BY 子句中:

SELECT CASE WHEN followup_date IS NULL THEN 2 
            WHEN followup_date < '2022-03-24' THEN 1 
            ELSE 0 END AS sort_bucket, 
  id, followup_date 
FROM `activity` 
ORDER BY sort_bucket ASC, followup_date ASC

输出:

+-------------+----+---------------+
| sort_bucket | id | followup_date |
+-------------+----+---------------+
|           0 |  3 | 2022-03-24    |
|           0 |  4 | 2022-03-25    |
|           0 |  5 | 2022-03-26    |
|           1 |  6 | 2022-03-13    |
|           1 |  1 | 2022-03-22    |
|           1 |  2 | 2022-03-23    |
|           2 |  7 | NULL          |
|           2 |  8 | NULL          |
+-------------+----+---------------+