sql - 选择所有引用的表

标签 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);

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

最佳答案

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

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

关于sql - 选择所有引用的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12808963/

相关文章:

SQL 查询显示最常订购的产品

sql - 在sql中模拟Excel网络日

mysql - SQL错误(1242): Subquery returns more than 1 row - Not fixable with (IN) or a JOIN (I think?)

database - 如何安装/更新到 Postgres 9.4?

postgresql - 从命令行使用 postgresql 获取身份验证失败错误

sql - 更新与 SQL Server 中其他列对应的列

MySQL:SELECT EXISTS() AS field WHERE field = x

django - 统计Django中具有一定值的相关对象的个数

sql - 如何在 PostgreSQL 中获取前一个工作日?

postgresql - 如何从 CSV 为 PostgreSQL 副本生成模式