Find the referenced table name using table, field and schema name

前端 未结 1 928
深忆病人
深忆病人 2020-12-12 05:27

I have a requirement where I need to find the referenced table name (Primary key table name) by a particular field in a table (Foreign key table) using this field name, tabl

相关标签:
1条回答
  • 2020-12-12 05:52

    If you don't need this to be portable to another RDBMS it is much faster and simpler to use the catalog tables in pg_catalog instead of the standard information schema:

    SELECT c.confrelid::regclass::text AS referenced_table
         , c.conname AS fk_name
         , pg_get_constraintdef(c.oid) AS fk_definition
    FROM   pg_attribute a 
    JOIN   pg_constraint c ON (c.conrelid, c.conkey[1]) = (a.attrelid, a.attnum)
    WHERE  a.attrelid = '"Schema2"."TableB"'::regclass   -- table name
    AND    a.attname  = 'A_Id'                           -- column name  
    AND    c.contype  = 'f'
    ORDER  BY conrelid::regclass::text, contype DESC;
    

    Returns:

     referenced_table | fk_name  |  fk_definition
    ------------------+-------------------------+----------------------------------------------
     Schema1.TableA   | b1_fkey  | FOREIGN KEY ("B_id") REFERENCES "Schema1"."TableA"("A_id")
    

    Notes

    • The additional two columns are for orientation only. According to your Q, you only need the first column.

    • This returns all referenced tables by all foreign keys involving the given column name - including FK constraints on multiple columns.

    • The name is automatically schema-qualified or not according to the visibility set by the current search_path. The name is also escaped where needed (illegal or upper case characters, reserved words, ...) automatically, too.

    Check out details of pg_constraint and pg_attribute in the manual. And more about object identifier types as well.

    Related:

    • PostgreSQL drop constraint with unknown name
    • Retrieving all PK and FK
    0 讨论(0)
提交回复
热议问题