概述
ORDER BY
语句依据指定列对工作表记录进行排序。
<order by statement> ::=
"ORDER BY" <sort specification> [ { "," <sort specification> }... ]
<sort specification> ::=
<value expression> [ "ASC" | "DESC" ] [ "NULLS FIRST" | "NULLS LAST" ]
详情
- 默认使用
ASC
(升序);若想反转顺序,可显式使用关键词DESC
(降序)。 - 使用
NULLS FIRST
和NULLS LAST
可控制null
值排在非null
值之前还是之后。若明确null
值排序时:ASC
默认使用NULLS LAST
DESC
默认使用NULLS FIRST
示例图

CREATE GRAPH myGraph {
NODE Paper ({title string, score uint32, author string, publisher string}),
EDGE Cites ()-[{weight uint32}]->()
} PARTITION BY HASH(Crc32) SHARDS [1]
INSERT (p1:Paper {_id:'P1', title:'Efficient Graph Search', score:6, author:'Alex', publisher:'PulsePress'}),
(p2:Paper {_id:'P2', title:'Optimizing Queries', score:9, author:'Alex'}),
(p3:Paper {_id:'P3', title:'Path Patterns', score:7, author:'Zack', publisher:'BrightLeaf'}),
(p1)-[:Cites {weight:2}]->(p2),
(p2)-[:Cites {weight:1}]->(p3)
根据属性排序
MATCH (n:Paper)
ORDER BY n.score
RETURN n.title, n.score
结果:
n.title | n.score |
---|---|
Efficient Graph Search | 6 |
Path Patterns | 7 |
Optimizing Queries | 9 |
根据点、边变量排序
指定点、边变量时,根据点或边的_uuid
值进行排序。
MATCH (n:Paper)
RETURN n.title, element_id(n) ORDER BY n
结果:
n.title | element_id(n) |
---|---|
Optimizing Queries | 8718971077612535810 |
Efficient Graph Search | 8791028671650463745 |
Path Patterns | 12033620403357220867 |
根据表达式排序
MATCH p = (:Paper)->{1,2}(:Paper)
RETURN p, path_length(p) AS length ORDER BY length DESC
结果:
p | length |
---|---|
![]() |
2 |
![]() |
1 |
![]() |
1 |
多级排序
指定多个排序依据时,工作表首先依据第一个进行排序;对于相等的值,再依据下一个进行排序,以此类推。
MATCH (n:Paper)
RETURN n.title, n.author, n.score
ORDER BY n.author DESC, n.score
结果:
n.title | n.author | n.score |
---|---|---|
Path Patterns | Zack | 7 |
Efficient Graph Search | Alex | 6 |
Optimizing Queries | Alex | 9 |
排序后删除和保留记录
在ORDER BY
语句后使用SKIP
或LIMIT
语句,可跳过工作表开头指定数量的记录,或限制保留的记录数。
返回得分第二和第三高的两篇论文题目:
MATCH (n:Paper)
RETURN n.title, n.score
ORDER BY n.score DESC SKIP 1 LIMIT 2
结果:
n.title | n.score |
---|---|
Path Patterns | 7 |
Efficient Graph Search | 6 |
Null值排序
返回得分第二和第三高的两篇论文题目,如果有null
值,排在最前面:
MATCH (n:Paper)
RETURN n.title, n.publisher
ORDER BY n.publisher NULLS FIRST
结果:
n.title | n.score |
---|---|
Optimizing Queries | null |
Path Patterns | BrightLeaf |
Efficient Graph Search | PulsePress |