gpt4 book ai didi

sql - Postgres : Find "from this table" foreign keys (Faster alternative)

转载 作者:行者123 更新时间:2023-11-29 12:06:09 24 4
gpt4 key购买 nike

有没有比 this 更快的替代品? :

在我们的服务器上花将近 1 分钟的时间。

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';

也许使用 pg_class 元数据?谢谢。

最佳答案

有一个问题:一个外键可以在2个或更多列上(FOREIGN KEY (b, c) REFERENCES other_table (c1, c2))。您需要首先指定如何处理这些 key 。

这是我用来获取所有外键的查询,但它仅适用于简单的(一列)外键。

SELECT pgcon.conname as constraint_name, 
cast(pgcon.conrelid as regclass) as table_name,
cast(pgcon.confrelid as regclass) as foreign_table_name,
pga1.attname as column_name,
pga2.attname as foreign_column_name
FROM pg_constraint pgcon
JOIN pg_attribute pga1 on (pgcon.conrelid = pga1.attrelid
and pga1.attnum = any(pgcon.conkey))
JOIN pg_attribute pga2 on (pgcon.confrelid = pga2.attrelid
and pga2.attnum = any(pgcon.confkey))
WHERE pgcon.conrelid = cast('table_name_here' as regclass)
AND pgcon.contype = 'f'

关于sql - Postgres : Find "from this table" foreign keys (Faster alternative),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13400457/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com