PostgreSQL中比较冷门的特性(一)
发布日期:2021-05-08 12:27:36 浏览次数:17 分类:精选文章

本文共 2082 字,大约阅读时间需要 6 分钟。

Listen与通知(Listen & Notify)

PostgreSQL内置了一个简单但强大的发布-订阅通知系统。你可以向正在侦听特定主题的客户端广播消息。这种机制不需要轮询数据库,而是通过Postgres服务器异步推送通知给客户端。以下是使用listen和notify的基本原理:

  • listen channel:客户端订阅特定主题的通知。
  • notify channel [payload]:发布消息到所有订阅的客户端,payload为可选的消息内容。

例如:

postgres=# LISTEN postgres;postgres=# NOTIFY postgres,'hello world';

收到的通知类似于:

Asynchronous notification "postgres" with payload "hello world" received from server process with PID 2429.

表继承(Table Inheritance)

PostgreSQL的表继承是其独特的特性,允许一个表继承另一个表的数据和约束。例如:

postgres=# CREATE TABLE people(name text, age int, sex boolean);postgres=# CREATE TABLE stuff(id int) INHERITS(people);

插入stuff表数据后,people表也会显示这些数据:

postgres=# INSERT INTO stuff VALUES('zhang',19,true,1);postgres=# INSERT INTO stuff VALUES('wang',14,false,2);postgres=# INSERT INTO stuff VALUES('lee',23,true,3);

查询people表:

postgres=# SELECT * FROM people;

结果显示所有stuff表数据。

注意:查询父表时会包含所有子表数据,但查询子表时只显示其自身的数据。要仅查询父表,可以使用ONLY关键字:

postgres=# SELECT * FROM ONLY people;

外部数据包装器(Foreign Data Wrapper)

FDW(外部数据包装器)允许PostgreSQL访问外部数据源,例如另一个PostgreSQL实例或外部数据库。例如,使用postgres_fdw可以连接到其他PostgreSQL服务器:

postgres=# CREATE EXTENSION postgres_fdw;postgres=# CREATE SERVER ...;postgres=# CREATE FOREIGN TABLE other_db.table_name (...) SERVER ...;

这样,你可以在本地创建一个虚拟表,连接到远程数据库,实现数据的局部化访问和操作。

分区表(Partitioned Tables)

PostgreSQL通过表继承实现分区表功能。从PostgreSQL 10开始,支持基于列值的分区,例如按日期分区:

postgres=# CREATE TABLE matches(match_num int, match_day date) PARTITION BY RANGE(match_day);postgres=# CREATE TABLE matches_201801 PARTITION OF matches FOR VALUES FROM ('2018-01-01') TO ('2018-02-01');

插入数据后,各子表数据会被正确路由:

postgres=# INSERT INTO matches VALUES (878178,'2018-01-25');postgres=# INSERT INTO matches VALUES (512716,'2018-02-03');

查询单个子表或所有子表时,可以看到数据分布。

Range数据类型

PostgreSQL提供内置的Range数据类型,用于表示多个值的范围。例如int4range表示4字节整数范围:

postgres=# CREATE TABLE weights(item text, weight int4range);postgres=# INSERT INTO weights VALUES('cup','[2,5)');postgres=# INSERT INTO weights VALUES('desk','[30,45)');

查询范围内的数据:

postgres=# SELECT * FROM weights WHERE weight && int4range(10,50);

结果会显示符合条件的记录。

通过以上特性,PostgreSQL不仅提供了强大的数据操作能力,还支持高效的数据管理和扩展。

上一篇:PostgreSQL中比较冷门的特性(二)
下一篇:psql和server版本不一致的问题

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2025年04月29日 18时50分39秒