Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:读取PostgreSQL表的关系(外键表)_Python_Postgresql - Fatal编程技术网

Python:读取PostgreSQL表的关系(外键表)

Python:读取PostgreSQL表的关系(外键表),python,postgresql,Python,Postgresql,我需要使用python阅读postgres数据库模式。我已经可以使用 cursor.execute( "select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';") 以及 我还想阅读表之间的关系。有人知道怎么做吗?请尝试使用此查询,它应该可以正常工作: cursor.execute("""SELECT tc.constraint_name, tc.table_name, kc

我需要使用python阅读postgres数据库模式。我已经可以使用

cursor.execute(
  "select relname 
  from pg_class 
  where relkind='r' and relname !~ '^(pg_|sql_)';")
以及


我还想阅读表之间的关系。有人知道怎么做吗?

请尝试使用此查询,它应该可以正常工作:

cursor.execute("""SELECT
    tc.constraint_name, tc.table_name, kcu.column_name, 
    ccu.table_name AS foreign_table_name,
    ccu.column_name AS foreign_column_name 
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu
      ON tc.constraint_name = kcu.constraint_name
    JOIN information_schema.constraint_column_usage AS ccu
      ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY' AND tc.table_name='+ table_name +'""")
我将从information\u schema.key\u column\u用法和information\u schema.table\u约束开始。请特别注意列约束模式和表模式。可以在多个架构中使用相同的表名。
cursor.execute("""SELECT
    tc.constraint_name, tc.table_name, kcu.column_name, 
    ccu.table_name AS foreign_table_name,
    ccu.column_name AS foreign_column_name 
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu
      ON tc.constraint_name = kcu.constraint_name
    JOIN information_schema.constraint_column_usage AS ccu
      ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY' AND tc.table_name='+ table_name +'""")