2

有没有更快的替代方案

在我们的服务器上花费将近 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 元数据?,谢谢。

4

3 回答 3

2

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

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

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'
于 2012-11-15T16:58:23.617 回答
1

要获得相同的结果:

SELECT conname
      ,c.conrelid::regclass AS table_name
      ,(SELECT string_agg(a.attname, ', ') FROM pg_attribute a
        WHERE  a.attrelid = c.conrelid
        AND    a.attnum = ANY(c.conkey)) AS columns
      ,c.confrelid::regclass
      ,(SELECT string_agg(a.attname, ', ') FROM pg_attribute a
        WHERE  a.attrelid = c.confrelid
        AND    a.attnum = ANY(c.confkey)) AS foreign_columns
FROM   pg_constraint c
WHERE  c.conrelid = 'mytable'::regclass
AND    c.contype = 'f'
ORDER  BY c.conname;

涵盖源自该表的外

于 2012-11-15T23:09:41.077 回答
0

您可以使用以下查询:

SELECT conname, pg_get_constraintdef(oid)
  FROM pg_constraint
 WHERE confrelid='mytable'::regclass;

confrelid仅设置为外键并包含引用的表

这一点的灵感来自这个 depesz 的帖子

于 2012-11-15T20:42:28.170 回答