如何从一个数据库查询到另一个数据库

时间:2016-11-28 10:42:40

标签: sql postgresql

使用postgres我写了一个查询来列出数据库中的表

SELECT table_name
FROM information_schema.tables
WHERE table_type = 'BASE TABLE'
AND table_schema NOT IN
('pg_catalog', 'information_schema');

查询返回错误数据库的结果。它会自动从postgres中的数据库列表中选择第一个数据库。

如何指定要查询的数据库? ' j220190_data'是要查询的数据库

我尝试过这样的事情:

    SELECT table_name
FROM information_schema.tables
WHERE Databases = 'j220190_data'
AND table_schema NOT IN
('pg_catalog', 'information_schema');

SELECT table_name
FROM information_schema.tables
WHERE table_type = 'BASE TABLE' AND
WHERE Databases = 'j220190_data'
AND table_schema NOT IN
('pg_catalog', 'information_schema');

2 个答案:

答案 0 :(得分:0)

连接到postgres时选择数据库;
例如:

psql mydb

并且在您发布选择之后,因为当您尝试使用此选择时,postgres会检查默认数据库。

答案 1 :(得分:0)

如果我理解正确,您可以使用dblink()查询其他数据库。

创建扩展程序CREATE EXTENSION dblink;

SELECT tbl.*
FROM dblink('dbname=DB1 port=5432   
            host=localhost user=usr password=123', 'SELECT table_name
FROM information_schema.tables
WHERE table_type = ''BASE TABLE'' 
AND table_schema NOT IN(''pg_catalog'', ''information_schema'');') 
AS tbl(table_name varchar(30));
相关问题