数据排序
最近更新时间: 2025-02-18 16:02:00
- 按某一列排序。
postgres=# INSERT into tbase (id,nickname) VALUES(1,'hello TDSQL PG');
INSERT 0 1
postgres=# INSERT into tbase (id,nickname) VALUES(2,'TDSQL PG好');
INSERT 0 1
postgres=# INSERT into tbase (id,nickname) VALUES(1,'TDSQL PG分布式数据库的时代来了');
INSERT 0 1
postgres=# select * from tbase order by id;
id | nickname
----+-----------------------------
1 | hello TDSQL PG
1 | TDSQL PG分布式数据库的时代来了
2 | TDSQL PG好
(3 rows)
- 按第一列排序。
postgres=# select * from tbase order by 1;
id | nickname
----+-----------------------------
1 | hello TDSQL PG
1 | TDSQL PG分布式数据库的时代来了
2 | TDSQL PG好
(3 rows)
- 按id升级排序,再按nickname降序排序。
postgres=# select * from tbase order by id,nickname desc;
id | nickname
----+-----------------------------
1 | TDSQL PG分布式数据库的时代来了
1 | hello TDSQL PG
2 | TDSQL PG好
(3 rows)
- 效果与上面的语句一样。
postgres=# select * from tbase order by 1,2 desc;
id | nickname
----+-----------------------------
1 | TDSQL PG分布式数据库的时代来了
1 | hello TDSQL PG
2 | TDSQL PG好
(3 rows)
- 随机排序。
postgres=# select * from tbase order by random();
id | nickname
----+-----------------------------
1 | TDSQL PG分布式数据库的时代来了
2 | TDSQL PG好
1 | hello TDSQL PG
(3 rows)
- 计算排序。
postgres=# select * from tbase order by md5(nickname);
id | nickname
----+-----------------------------
2 | TDSQL PG好
1 | TDSQL PG分布式数据库的时代来了
1 | hello TDSQL PG
(3 rows)
- 排序子查询。
postgres=# select * from tbase order by (select id from tbase order by random() limit 1);
id | nickname
----+-----------------------------
1 | hello TDSQL PG
2 | TDSQL PG好
1 | TDSQL PG分布式数据库的时代来了
(3 rows)
- null值排序结果处理。
postgres=# insert into tbase values(4,null);
INSERT 0 1
null值记录排在最前面
postgres=# select * from tbase order by nickname nulls first;
id | nickname
----+-----------------------------
4 |
1 | hello TDSQL PG
1 | TDSQL PG分布式数据库的时代来了
2 | TDSQL PG好
(4 rows)
null值记录排在最后
postgres=# select * from tbase order by nickname nulls last;
id | nickname
----+-----------------------------
1 | hello TDSQL PG
1 | TDSQL PG分布式数据库的时代来了
2 | TDSQL PG好
4 |
(4 rows)
- 按拼音排序。
postgres=# select * from (values ('张三'), ('李四'),('陈五')) t(myname) order by myname;
myname
--------
张三
李四
陈五
(3 rows)
如果不加处理,则按汉字的utf8编码进行排序,不符合中国人使用习惯。
postgres=# select * from (values ('张三'), ('李四'),('陈五')) t(myname) order by convert(myname::bytea,'UTF-8','GBK');
myname
--------
陈五
李四
张三
(3 rows)
- 使用convert函数实现汉字按拼音进行排序。
postgres=# select * from (values ('张三'), ('李四'),('陈五')) t(myname) order by convert_to(myname,'GBK');
myname
--------
陈五
李四
张三
(3 rows)
- 使用convert_to函数实现汉字按拼音进行排序。
postgres=# select * from (values ('张三'), ('李四'),('陈五')) t(myname) order by myname collate "zh_CN.utf8";
myname
--------
陈五
李四
张三
(3 rows)
通过指定排序规则collact来实现汉字按拼音进行排序。