postgresSQL跨库查询
1.安装dblink 下载安装包 [postgresql11-contrib-11.3-1PGDG.rhel7.x86_64.rpm](https://www.showdoc.com.cn/server/api/attachment/visitfile/sign/c2c32be72510cfd615d63597c51c9f21 "[postgresql11-contrib-11.3-1PGDG.rhel7.x86_64.rpm") 下载之后重命名一下,执行命令安装
rpm -ivh postgresql11-contrib-11.3-1PGDG.rhel7.x86_64.rpm
如果安装失败,可以把[RPM-GPG-KEY-PGDG](https://www.showdoc.com.cn/server/api/attachment/visitfile/sign/11944b4e16194ad957b43540f7a179bf "[RPM-GPG-KEY-PGDG")文件(下载之后重命名一下)导入/etc/pki/rpm-gpg
文件夹
然后执行
rpm --import /etc/pki/rpm-gpg/RPM*
如果再次执行rpm -ivh postgresql11-contrib-11.3-1PGDG.rhel7.x86_64.rpm
失败,报错
安装[libxslt-1.1.28-6.el7.x86_64.rpm](https://www.showdoc.com.cn/server/api/attachment/visitfile/sign/bc02b3698509e585438247cc98bf5363 "[libxslt-1.1.28-6.el7.x86_64.rpm")(下载之后重命名一下)
rpm -ivh libxslt-1.1.28-6.el7.x86_64.rpm
再次执行rpm -ivh postgresql11-contrib-11.3-1PGDG.rhel7.x86_64.rpm
2.使用数据库连接工具执行SQL,哪个库需要跨库查询就在哪个库上执行
create extension dblink;
安装完成之后,可以在函数中看到dblink相关的扩展函数
或者使用
select * from pg_extension;
-查看pgsql数据库已安装的扩展
3.使用方式
--常规使用
select * from dblink('hostaddr=192.168.0.105 port=5432 dbname=yjtBackstagePermissions user=postgres password=123456','select "NikeName" from "People"') AS testTable ("NikeName" VARCHAR);
--如果不只是查询数据,而是需要修改数据库数据的情况下怎么弄呢?
1. 先执行dblink_connect保持连接
SELECT dblink_connect('mycoon','hostaddr=192.168.0.105 port=5432 dbname=yjtBackstagePermissions user=postgres password=123456');
2. 执行BEGIN命令
SELECT dblink_exec('mycoon', 'BEGIN');
3. 执行数据操作(update,insert,create等命令)
SELECT dblink_exec('mycoon', 'insert into tb1 select generate_series(10,20),''hello''');
SELECT dblink_exec('mycoon', 'insert into people(username,nikename) values ("张三","小三") ');
4. 执行事务提交
SELECT dblink_exec('mycoon', 'COMMIT');
5. 解除连接
SELECT dblink_disconnect('mycoon');
4.创建视图。方便查询使用-示例
create view xxxx_orders_view AS
select * from dblink('host=127.0.0.1 port=5432 dbname=zszq user=postgres password=123456','select * from xxxx_orders;') as xxxx_orders(
uuid varchar(50),
m_uuid varchar(50),
"fileId" varchar(50),
authcode varchar(255),
oa_result text,
m_number varchar(50),
oa_status varchar(255),
create_time varchar(50),
update_time varchar(50)
);