如何在PostgreSQL Server中查看表关系?

vaj7vani  于 2022-11-29  发布在  PostgreSQL
关注(0)|答案(3)|浏览(303)

如何在PostgreSQL服务器中查看表关系?我已经尝试了几次,两年多前在PostgreSQL服务器中查找表关系,但没有得到任何帮助。那么有什么方法可以在SQL服务器或Access中找到相同的表关系?或者是否可以在PostgreSQL服务器中查看表关系?

4uqofj5v

4uqofj5v1#

如果要列出从表开始的所有关系,则必须搜索外键。在Postgresql中,它意味着搜索约束。
它在这个问题中得到了解决:SQL to list table foreign keys
王斌回答:

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='mytable';
rt4zxlrg

rt4zxlrg2#

您可以尝试使用DataGrip或pgAdmin之类的UI。我在Postgres应用程序上使用DataGrip。您可以简单地尝试使用postgres交互式shell -- psql。
祝你好运

deikduxw

deikduxw3#

我知道这个问题并不完全是关于这个的,但是我认为很多人来到这里都是为了寻找一种简单的方法来查看使用不同数据类型的表之间的关系(比如parent id与bigint和child外键int,反之亦然)。
下面是一种快速方法,可以在父表和子表之间发现所有类型不同的列:

SELECT
tc.constraint_name, tc.table_name, kcu.column_name, 
ccu.table_name AS foreign_table_name,
ccu.column_name AS foreign_column_name,
cf.data_type AS child_data_type, 
cp.data_type AS parent_data_type
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
JOIN information_schema.tables as t
    on t.table_name = tc.table_name and t.table_catalog  = tc.table_catalog and t.table_schema = tc.table_schema 
JOIN information_schema.columns as cf
    on cf.table_name = tc.table_name and cf.column_name = kcu.column_name and cf.table_catalog = tc.table_catalog and cf.table_schema = tc.table_schema 
JOIN information_schema.columns as cp
    on cp.table_name = ccu.table_name and cp.column_name = ccu.column_name and cp.table_catalog = ccu.table_catalog and cp.table_schema = ccu.table_schema 
WHERE constraint_type = 'FOREIGN KEY'
and cf.data_type <> cp.data_type;

好好享受吧!

相关问题