1. 程式人生 > 其它 >postgresql 資料庫 與TimescaleDB 時序庫 join 在一起

postgresql 資料庫 與TimescaleDB 時序庫 join 在一起

技術標籤:postgresqlTimescaleDBpostgresql資料庫經驗分享

postgresql 資料庫 與TimescaleDB 時序庫 join 在一起

之前在CSDN閱讀資料時,發現有人問怎麼把 postgresql資料庫 的表 跟TimescaleDB 時序庫的表 join在一起,正好我在查詢資料的時候遇到過這個問題 ,我說一下我的解決方案
我選擇的是postgresql資料庫的fdw功能(postgres_fdw外掛

**

一 安裝postgres_fdw外掛

1.1安裝postgres_fdw外掛
**

su – postgres
-bash-4.2$ psql
postgres=
# \c hrmwv2 #(資料庫名字) Create extension "postgres_fdw";

也可以在連線資料庫的工具中執行
在這裡插入圖片描述
1.2 檢視已安裝外掛命令

select * from pg_available_extensions;

**

二 建立外部連線(TimescaleDB資料庫)

**
需要連線TimescaleDB資料庫 資訊:(虛構)
ip :170.0.0.32 埠:5432
資料庫名: hrmw 使用者名稱:postgres

2.1創建於TimescaleDB的外部連結

--建立外部伺服器
-- 括號裡的三個引數,分別是timescaledb的ip、埠和資料庫名稱
CREATE SERVER timescale_db FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host '170.0.0.32', port '5432', dbname 'hrmw'); --建立使用者對映 -- 括號裡的兩個引數,分別是timescaledb資料庫的使用者名稱、密碼 create user mapping for postgres server timescale_db options(user 'postgres', password '資料庫密碼');

2.2 檢視外部連結命令

select * from pg_foreign_server;

結果:
在這裡插入圖片描述

#一般fwd出問題就看看這裡 是否配置正確
srvname:--你建的連結名
srvoptions:--你要連結的timescaledb時序庫的資訊

2.3 刪除fdw外部連結
這裡刪除要一步步的刪或者直接使用級聯刪除的方法

drop  server timescale_db CASCADE;

如果不用級聯,直接drop timescale_db ,是刪不掉的,報錯如下:

> ERROR:  cannot drop server timescale_db because other objects depend on it
DETAIL:  user mapping for postgres on server timescale_db depends on server timescale_db
HINT:  Use DROP ... CASCADE to drop the dependent objects too.

**

三 建立外部表

**
3.1 建立外部表(你需要join TimescaleDB的 那張表:一模一樣的,可以是超表)

CREATE FOREIGN TABLE tb_fdw_timescale_target 
 (
 collect_time timestamp(6),
  id varchar(36) ,
  value numeric(12,2) ,
  file_no int4 ,
  create_time timestamp(6)
 )
 server timescale_db --你建立的外部連結名字
 options (table_name '時序庫的表名');

如果你沒有進到pg相應的模式下,需指定模式
3.2 刪除外部表命令
跟普通表一樣

DROP FOREIGN TABLE tb_fdw_timescale_target;

**

四 檢查外部表

**
去業務開啟你建的外部表是否有資料, 如果有資料則表明外部表建立成功,你就可以跟業務庫的一起join了

在這裡插入圖片描述
這個錯誤就是你之前配置要連線的TimescaleDB資料庫 配置錯誤了,改的話我目前知道的是隻能級聯刪除fdw,重新建了

當然 fdw的功能遠遠不止這些,還可以很Mysql資料庫,oracle等資料庫