简体   繁体   English

使用Postgres从多个模式中选择(检索)所有记录

[英]Select (retrieve) all records from multiple schemas using Postgres

I have a PostgreSQL database with some schemas, like below: 我有一个PostgreSQL数据库,其中包含一些模式,如下所示:

My_Database
 |-> Schemas
    |-> AccountA
    |-> AccountB
    |-> AccountC
    |-> AccountD
    |-> AccountE
           .
           .
           .
    |-> AccountZ

All schemas have a table called product which has a column called title . 所有模式都有一个名为product的表,其中有一个名为title的列。 I would like to know if is possible to execute a select statement to retrieve all records from all schemas with a certain conditional. 我想知道是否可以执行select语句来检索具有特定条件的所有模式的所有记录。

The only way I found until now is to run a query account by account, like below. 我到目前为止找到的唯一方法是按帐户运行查询帐户,如下所示。

SET search_path TO AccountA;

SELECT title FROM product WHERE title ILIKE '%test%';

Schemas are created dynamically , so I don't know their names or how many of them exist. 模式是动态创建的 ,因此我不知道它们的名称或存在多少名称。

With inheritance like @Denis mentioned , this would be very simple. @Denis提到的 继承 ,这将非常简单。 Works for Postgres 8.4, too. 也适用于Postgres 8.4。 Be sure to consider the limitations . 一定要考虑这些限制

Basically, you would have a master table, I suppose in a master schema: 基本上,你会有一个主表,我想在一个主模式中:

CREATE TABLE master.product (title text);

And all other tables in various schemata inherit from it, possibly adding more local columns: 各种模式中的所有其他表都继承自它,可能会添加更多本地列:

CREATE TABLE a.product (product_id serial PRIMARY KEY, col2 text)
INHERITS (master.product);

CREATE TABLE b.product (product_id serial PRIMARY KEY, col2 text, col3 text)
INHERITS (master.product);

etc. 等等

The tables don't have to share the same name or schema. 表不必共享相同的名称或架构。
Then you can query all tables in a single fell swoop: 然后你可以一举查询所有表格

SELECT title, tableoid::regclass::text AS source
FROM   master.product
WHERE  title ILIKE '%test%';

tableoid::regclass::text ? tableoid::regclass::text
That's a handy way to tell the source of each row. 这是一种方便的方式来告诉每一行的来源。 Details: 细节:

SQL Fiddle. SQL小提琴。

You basically want a union all: 你基本上想要一个联盟:

SELECT title FROM AccountA.product WHERE title ILIKE '%test%'
UNION ALL
SELECT title FROM AccountB.product WHERE title ILIKE '%test%'
UNION ALL
...;

You can do so automatically by using dynamic SQL and the catalog to locate all AccountXYZ schemas that have a products table. 您可以使用动态SQL和目录自动执行此操作,以查找具有products表的所有AccountXYZ架构。

Alternatively, create a AllAccounts schema with similar tables as the ones in individual schemas, and use table inheritance. 或者,使用与各个模式中的表类似的表创建AllAccounts模式,并使用表继承。

Note that neither will tell you which schema the data is from, however. 但请注意,两者都不会告诉您数据来自哪个架构。 In the former case, this is easy enough to add; 在前一种情况下,这很容易添加; not so much in the latter unless you add an extra column. 除非你添加一个额外的列,否则在后者中没有那么多。

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

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