选择所有引用的表

时间:2012-10-09 21:51:31

标签: sql postgresql

例如:说,我有2个模式和4个表创建为

    create table a.foo(
      id integer primary key,
      val integer);

    create table b.main(
      id serial primary key,
      val integer references a.foo(id));

    create table b.foo(
      k integer primary key references b.main(id),
      v timestamp with time zone);

    create table b.bar(
      k integer primary key references b.main(id),
      v timestamp with time zone);

我正在寻找的Psuedo代码:选择所有引用b.main.id的表;

结果如下:

    b.main.id | b.main.val | b.foo.k | b.foo.v | b.bar.k | b.bar.v
       1           1           1      TimeStamp    1      TimeStamp
       2           1           2        ....       2        ....

现在我已将此查询实现为:

   select * from b.main,
            (select *
               from b.foo,
                   (select * from b.bar where b.bar.v > somedate) as morebar
              where b.bar.k = b.foo.k) as morefoo
    where b.main.id = b.foo.k;

回到问题。 Postgres中是否有一项功能允许我们对引用主键的所有表执行选择?就我而言,所有引用b.main.id的表。

我搜索了Postgresql文档,但还没有找到我正在寻找的内容。建议?

2 个答案:

答案 0 :(得分:1)

我还没有找到一种方法来自动选择引用表主键的其他表。您似乎仍然需要在查询中手动提及/键入其他表,但这是使用join的查询的简短版本:

select *
from b.main a, b.foo b, b.bar c
where a.id = b.k
and a.id = c.k

select a.*, b.*, c.*
from b.main as a
inner join b.foo as b on a.id = b.k
inner join b.bar as c on a.id = c.k

答案 1 :(得分:0)

您可以尝试:

SELECT tc.constraint_name, tc.table_name, kcu.column_name,
       ccu.table_schema AS foreign_schema,
       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 ccu.table_schema = 'b'
AND ccu.table_name='main'
AND ccu.column_name = 'id';