简体   繁体   English

PostgreSQL FOREIGN KEY与第二个数据库

[英]PostgreSQL FOREIGN KEY with second database

I'm running the following queries on PostgreSQL 9.3: 我在PostgreSQL 9.3上运行以下查询:

CREATE TABLE "app_item" 
  ( 
     "id"          SERIAL NOT NULL PRIMARY KEY, 
     "location_id" UUID NOT NULL 
  ); 

CREATE INDEX app_item_e274a5da 
  ON "app_item" ("location_id"); 

ALTER TABLE "app_item" 
  ADD CONSTRAINT app_item_location_id_5cecc1c0b46e12e2_fk_fias_addrobj_aoguid 
  FOREIGN KEY ("location_id") REFERENCES "fias_addrobj" ("aoguid") deferrable 
  initially deferred;

Third query returns: 第三个查询返回:

ERROR: relation "fias_addrobj" does not exist 错误:关系“fias_addrobj”不存在

  • app_item - table in first database app_item - 第一个数据库中的表
  • fias_addrobj - table in second database fias_addrobj - 第二个数据库中的表

How to do correct query with this databases? 如何使用此数据库进行正确查询?

I've not had occasion to use this myself, but you might want to look into Foreign Data Wrappers , which are essentially the successor to dblink . 我自己没有机会使用它,但你可能想要查看外部数据包装器 ,它本质上是dblink的后继者。 In particular, postgres-fdw . 特别是postgres-fdw

Once the general setup of the fdw is in place (steps 1-3 in the link above), you could create a foreign table via CREATE FOREIGN TABLE , defined like the table in your remote DB, and then use that table as part of the foreign key CONSTRAINT , and see if it works. 一旦外籍家政工人的常规安装到位(步骤在上面的链接1-3),你可以通过创建一个外部表 CREATE FOREIGN TABLE ,就像在远程数据库的表中定义,然后使用该表作为的一部分外键 CONSTRAINT ,看它是否有效。

If that doesn't work, another option would be to have a process which ETL's the data (say, via a Python script) from the remote server over to the local server (say, on an hourly or daily basis, depending on the size), and then you would have a true local table to use in the foreign key CONSTRAINT . 如果这不起作用,另一种选择是将ETL的数据(例如,通过Python脚本)从远程服务器传输到本地服务器(例如,每小时或每天,取决于大小) ),然后你将有一个真正的本地表用于外键 CONSTRAINT It wouldn't be real-time, but depending on your needs, may suffice. 这不是实时的,但根据您的需要,可能就足够了。

A local table must be referenced 必须引用本地表

However, as stated within the below link, you could maybe use a trigger which uses a cross server join (facilitated by dblink ) to simulate the built-in methods for constraining? 但是,如下面的链接所述,您可以使用一个使用跨服务器连接的触发器(由dblink促成)来模拟内置的约束方法?

For instance, you could have a trigger set up that on INSERT , checks to see if a given FK exists to aid with enforcing referential integrity, or on DELETE to cascade 例如,您可以在INSERT上设置触发器,检查是否存在给定的FK以帮助强制执行参照完整性,或者在DELETE进行级联

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=101322 http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=101322

PS Would avoid this at all costs. PS会不惜一切代价避免这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM