MySql order by multiple columns 首先对 NULL 条目进行排序

MySql order by multiple columns sorting NULL entries at first

我有一个 table,如 SQL Fiddle 所示。

CREATE TABLE `test` (
  `id` varchar(250) NOT NULL,
  `name` varchar(512) NOT NULL,
  `description` text NOT NULL,
  `priority` int(11) DEFAULT NULL,
  `created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


 INSERT INTO `test` (`id`, `name`, `description`, `priority`, `created_date`) VALUES
('1', 'John', 'kasdjkaksdj', 3, '2018-07-12 07:37:25'),
('2', 'Doe', 'updations', 1, '2018-07-12 08:56:27'),
('3', 'Matt', 'sdasd', NULL, '2018-07-12 09:09:08'),
('4', 'Jiss', 'vghjgfghj', 1, '2018-07-13 12:33:19'),
('5', 'Noel', 'sdfsdf', NULL, '2018-07-13 12:33:29');

priority 列默认为 NULL。用户可以为此列指定任何整数值。我想根据 priority asc 对 table 进行排序,其余记录(具有 NULL 优先级)按 created_date asc.

排序

我试过查询

SELECT * FROM `test` ORDER BY priority, created_date 

结果:

id    name    description priority    created_date

3     Matt    sdasd        (null)      2018-07-12T09:09:08Z

5     Noel    sdfsdf       (null)      2018-07-13T12:33:29Z

2     Doe     updations     1          2018-07-12T08:56:27Z

4     Jiss    vghjgfghj     1          2018-07-13T12:33:19Z

1     John    kasdjkaksdj   3          2018-07-12T07:37:25Z

但这是显示优先级,首先是 NULL 个值,然后是按优先级排序的记录。

异常结果:

id    name    description priority    created_date

2     Doe     updations     1          2018-07-12T08:56:27Z

4     Jiss    vghjgfghj     1          2018-07-13T12:33:19Z

1     John    kasdjkaksdj   3          2018-07-12T07:37:25Z

3     Matt    sdasd        (null)      2018-07-12T09:09:08Z

5     Noel    sdfsdf       (null)      2018-07-13T12:33:29Z

谁能帮我找到正确的查询。提前致谢。

你可以试试这个代码

SELECT * FROM `test` ORDER BY ISNULL(priority) ,priority, created_date

DEMO

您的查询工作正常,但只有一个问题:

您只需在 ORDER BY:

之后添加 "name"

供参考:转到demo