Select (retrieve) all records from multiple schemas using Postgres

后端 未结 2 1397
囚心锁ツ
囚心锁ツ 2020-11-30 13:27

I have a PostgreSQL database with some schemas, like below:

My_Database
 |-> Schemas
    |-> AccountA
    |-> AccountB
    |-> AccountC
    |->         


        
2条回答
  •  渐次进展
    2020-11-30 13:42

    With inheritance like @Denis mentioned, this would be very simple. Works for Postgres 8.4, too. 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?
    That's a handy way to tell the source of each row. Details:

    • Find out which schema based on table values

    SQL Fiddle.

提交回复
热议问题