3

例如:说,我有 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);

我正在寻找的伪代码:选择所有引用 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 文档,但还没有找到我要找的东西。建议?

4

2 回答 2

2

我还没有找到一种方法来自动选择引用表主键的其他表。看来您仍然必须在查询中手动提及/键入另一个表,但这是使用连接的查询的简短版本:

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
于 2012-10-09T22:04:25.103 回答
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';
于 2012-10-10T10:41:18.580 回答