我有下表,我按prioridad
和id_agenda
排序,顺序必须如下 Priority ASC 和id_agenda
DESC (如果数据没有优先级,那么它必须低于那些有优先级的数据)。
sql
CREATE TABLE IF NOT EXISTS `ACT_Agenda` (
`id_agenda` int(11) NOT NULL AUTO_INCREMENT,
`prioridad` int(11) DEFAULT NULL,
`actividad` text,
PRIMARY KEY (`id_agenda`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=83 ;
INSERT INTO `ACT_Agenda` (`id_agenda`, `prioridad`, `actividad`) VALUES
(51, 1, 'act1'),
(60, 2, 'act2'),
(62, 3, 'act3'),
(70, NULL, 'act4'),
(71, NULL, 'act5'),
这是我订购的代码。
$sql = "SELECT * FROM ACT_Agenda as a
ORDER BY prioridad DESC, id_agenda DESC ";
我的结果。sqlFiddle
---------------------------
|id |prioridad| actividad|
----|---------|-----------|
|62 | 3 |act1 | <--Debería ordenar por la primera prioridad
|60 | 2 |act2 |
|51 | 1 |act3 |
|71 | |act5 | <--Ultimo valor ingresado
|70 | |act4 |
|---|---------|-----------|
但是如果我按 ASC 优先级排序,则表是无序的,最后id
一个排在第一位。我想要这样的结果。
---------------------------
|id |prioridad| actividad|
----|---------|-----------|
|51 | 1 |act1 | <--Ordena por primera prioridad
|60 | 2 |act2 |
|62 | 3 |act3 |
|71 | |act5 | <--Ultimo valor ingresado
|70 | |act4 |
|---|---------|-----------|
prioridad
按order字段排序时ASC
,将 null 放在最前面。实现此目的的一种变体是将两个查询合并,首先是那些不为空的查询,然后将其他查询放在后面。请注意,查询第二部分中的括号很重要,因为否则它将最后一个应用于
order by
联合的结果,返回到原始情况。实际上,在 MySQL 中,NULL 被认为小于任何其他非 NULL 值,除非您
-
在 Order By 中的列名之前添加字符并且 ASC 更改为 DESC,反之亦然。见以下链接:不同SQL实现的比较SqlFiddle:sqlfiddle 示例
查询应该是这样的:
你会得到预期的结果。