MySql顺序由多列首先排序NULL条目

时间:2018-07-23 11:04:05

标签: mysql sorting isnull

我有一个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对表进行排序,对于其余记录(具有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

谁能帮助我找到正确的查询。预先感谢。

2 个答案:

答案 0 :(得分:1)

您可以尝试使用此代码

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

DEMO

答案 1 :(得分:0)

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

您只需在ORDER BY之后添加“名称”:

以供参考:转到demo