PostgreSQL 13新特性:fetch first with ties

PostgreSQL13中在select語句的fetch子句中新增了with ties選項,如:

Allow FETCH FIRST to use WITH TIES to return any additional rows that match the last result row

語法爲:

[ FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } { ONLY | WITH TIES } ]

具體介紹:
在這裏插入圖片描述
簡單來說其用法就是:
使用with ties後將會把order by的字段的最後一行後面的數據也列出來,因此要注意該參數必須和order by子句一起使用。

例子:
–建表

bill=# create table t(c1 int,c2 int,c3 int);
CREATE TABLE
bill=# insert into t select 1,2,generate_series(1,5);
INSERT 0 5
bill=# insert into t select 1,2,generate_series(1,5);
INSERT 0 5

–fetch only
指定只獲取2行。

bill=# select * from t order by c1,c2 offset 3 fetch first 2 row only;           
 c1 | c2 | c3 
----+----+----
  1 |  2 |  4
  1 |  2 |  5
(2 rows)

–fetch with ties
將原先c1=1,c2=2後面的滿足條件的數據也列舉出來了。

bill=# select * from t order by c1,c2 offset 3 fetch first 2 row with ties;                  
 c1 | c2 | c3 
----+----+----
  1 |  2 |  4
  1 |  2 |  5
  1 |  2 |  1
  1 |  2 |  2
  1 |  2 |  3
  1 |  2 |  4
  1 |  2 |  5
(7 rows)

–fetch with ties
需要注意的是,with ties列舉的行和order by的列有關,例如這裏我們order by的是c3列,前面的查詢最後一行是c3=3,那麼我們使用with ties也只能列出後面c3=3的行。

bill=# select * from t order by c3 offset 3 fetch first 2 row with ties;     
 c1 | c2 | c3 
----+----+----
  1 |  2 |  2
  1 |  2 |  3
  1 |  2 |  3
(3 rows)

最後再次提醒下,with ties只能和order by一起使用,否則會報錯哦!

bill=# select * from t offset 3 fetch first 2 row with ties;      
ERROR:  WITH TIES options can not be specified without ORDER BY clause

參考鏈接:
https://www.postgresql.org/docs/13/release-13.html
https://www.postgresql.org/docs/13/sql-select.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章