Postgres:找到“从这张桌子”外键(更快的替代品)

时间:2012-11-15 15:15:59

标签: sql postgresql postgresql-9.1

是否有更快的替代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元数据?,谢谢。

3 个答案:

答案 0 :(得分: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'

答案 1 :(得分: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;

从此表中包含来自的外键。

答案 2 :(得分:0)

您可以使用以下查询:

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

confrelid仅适用于外键和contains referenced table

这一点的灵感来自this depesz's post