当 from 语句后面的函数加上 WITH ORDINALITY 属性后,那么返回的结果集将增加一个整数列,这个整数列从 1 开始,并且按 1 递增,例如:
例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
francs=# select * from generate_series(4,6) with ordinality; generate_series | ordinality -----------------+------------ 4 | 1 5 | 2 6 | 3 (3 rows) francs=# select * from pg_ls_dir('pg_log') with ordinality limit 3; pg_ls_dir | ordinality ----------------------------------+------------ postgresql-2014-05-21_004931.csv | 1 postgresql-2014-05-21_005605.csv | 2 postgresql-2014-05-21_031005.csv | 3 (3 rows)
|
备注:新增的列名默认为 ordinality,也可以手工更改列名,如下:
指定列名
1 2 3 4 5 6 7
|
francs=# select * from pg_ls_dir('pg_log') with ordinality as t(csvfile_name,num) limit 3; csvfile_name | num ----------------------------------+----- postgresql-2014-05-21_004931.csv | 1 postgresql-2014-05-21_005605.csv | 2 postgresql-2014-05-21_031005.csv | 3 (3 rows)
|
备注: 文档上说这个属性对于返回结果集的函数特别有用,例如 unnest()。
Unnest()函数拆数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
francs=# select array[4,5,6,7]; array ----------- {4,5,6,7} (1 row) francs=# select * from unnest(array[4,5,6,7]) with ordinality; unnest | ordinality --------+------------ 4 | 1 5 | 2 6 | 3 7 | 4 (4 rows)
|
参考
原创文章,作者:carmelaweatherly,如若转载,请注明出处:https://blog.ytso.com/238060.html