多个order_by无法在psql中正确排序

时间:2019-02-07 14:02:44

标签: sql postgresql sql-order-by

尝试在以下查询中按两列排序。我想找到最近的人,然后按最高排名排序。

但是,当我运行此查询时,它仅返回最近的人,而不应用第二次排序

SELECT person.fullname, person.ranking_score ranking, ST_Distance(person.location, CAST(ST_SetSRID(ST_MakePoint(-0.1642618, 51.58763), 4326) AS geography(GEOMETRY,-1))) AS distance
FROM person
ORDER BY distance ASC, ranking DESC;

返回

 fullname |  ranking   |   distance    
----------+------+------------+-------
 User 1   |    2.62    | 1281.06710415
 User 2   |    5.218   | 1610.4042403
 User 3   |    3.72    | 3005.28625016
 User 4   |    2.82    | 3005.28625016
 User 5   |    6.826   | 3186.54245429

如您所见,正确的排序方式适用于距离,但排名不适用。

编辑:

我希望对距离进行初始排序,然后对结果集进行下一次排序?

 fullname |  ranking   |   distance    
----------+------+------------+-------
 User 5   |    6.826   | 3186.54245429
 User 2   |    5.218   | 1610.4042403
 User 3   |    3.72    | 3005.28625016
 User 4   |    2.82    | 3005.28625016
 User 1   |    2.62    | 1281.06710415

1 个答案:

答案 0 :(得分:1)

对于样本数据,您想按排名先后排序:

SELECT p.fullname, p.ranking_score ranking, 
       ST_Distance(p.location, CAST(ST_SetSRID(ST_MakePoint(-0.1642618, 51.58763), 4326) AS geography(GEOMETRY,-1))) AS distance
FROM person p
ORDER BY ranking DESC, distance ASC;

我怀疑在您的实际问题中,您可能会遇到限制距离的条件,或者想获取一定数量的最近的人的行。后一种情况需要子查询。