暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

PostgreSQL Oracle 兼容性 - order by INT(select位置 position)

digoal 2017-10-13
661

作者

digoal

日期

2017-10-13

标签

PostgreSQL , order by , 排序 , 字段 , 表达式 , 位置


背景

在一些Oracle的用户中,会问到是否支持order by INT这样的查询语法。它是什么意思呢?实际上就是按查询子句的第几个表达式进行排序。

https://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_10002.htm

ORDER [ SIBLINGS ] BY { expr | position | c_alias } [ ASC | DESC ] [ NULLS FIRST | NULLS LAST ] [, { expr | position | c_alias } [ ASC | DESC ] [ NULLS FIRST | NULLS LAST ] ]...

按 表达式、列别名、select位置排序。

PostgreSQL也支持这种语法。

PostgreSQL order by支持

PostgreSQL 天然支持 order by [字段、表达式、位置]。

```
[ ORDER BY expression [ ASC | DESC | USING operator ] [ NULLS { FIRST | LAST } ] [, ...] ]

Each expression can be the name or ordinal number of an output column (SELECT list item), or it can be an arbitrary expression formed from input-column values.
```

例子

1、按别名排序

```
postgres=# explain select relpages as ooo,* from pg_class order by ooo;
QUERY PLAN


Sort (cost=71.81..73.32 rows=602 width=737)
Sort Key: relpages
-> Seq Scan on pg_class (cost=0.00..44.02 rows=602 width=737)
(3 rows)
```

2、按SELECT中的位置排序

```
postgres=# explain select relpages,reltuples,relname from pg_class order by 2 limit 1;
QUERY PLAN


Limit (cost=47.03..47.03 rows=1 width=72)
-> Sort (cost=47.03..48.54 rows=602 width=72)
Sort Key: reltuples
-> Seq Scan on pg_class (cost=0.00..44.02 rows=602 width=72)
(4 rows)
```

3、按表达式排序

```
postgres=# explain select relpages,reltuples,relname from pg_class order by reltuples+relpages limit 1;
QUERY PLAN


Limit (cost=50.04..50.04 rows=1 width=80)
-> Sort (cost=50.04..51.55 rows=602 width=80)
Sort Key: ((reltuples + (relpages)::double precision))
-> Seq Scan on pg_class (cost=0.00..47.03 rows=602 width=80)
(4 rows)
```

参考

https://www.postgresql.org/docs/10/static/sql-select.html

https://www.postgresql.org/docs/10/static/sql-expressions.html#sql-syntax-collate-exprs

PostgreSQL 许愿链接

您的愿望将传达给PG kernel hacker、数据库厂商等, 帮助提高数据库产品质量和功能, 说不定下一个PG版本就有您提出的功能点. 针对非常好的提议,奖励限量版PG文化衫、纪念品、贴纸、PG热门书籍等,奖品丰富,快来许愿。开不开森.

9.9元购买3个月阿里云RDS PostgreSQL实例

PostgreSQL 解决方案集合

德哥 / digoal's github - 公益是一辈子的事.

digoal's wechat

文章转载自digoal,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论