【问题标题】:How to select top level schema in SQL?如何在 SQL 中选择顶级架构?
【发布时间】:2019-11-19 13:30:02
【问题描述】:

我在顶层有一个表 foo,在架构 bar 中有一个表 foo

使用此查询时:

select  *
from bar.foo
natural join foo
where foo.baz = 'test'

我得到错误:

ERROR:  table reference "foo" is ambiguous
LINE 4: where foo.baz = 'test'

我可以通过使用别名来解决这个问题:

select  *
from bar.foo
natural join foo as f
where f.baz = 'test'

但我想知道是否可以在不使用别名的情况下直接指定顶级架构(以使 SQL 清楚我不是在谈论 bar.foo)?例如这样的:

select  *
from bar.foo
natural join foo
where .foo.baz = 'test'

或者像这样:

select  *
from bar.foo
natural join foo
where root_schema.foo.baz = 'test'

【问题讨论】:

  • 不要使用natural join!明确列出join 条件!

标签: sql postgresql database-schema


【解决方案1】:

没有“顶级”架构这样的东西。所有模式都在同一级别。 搜索不合格的对象有一个优先级,由search_path

定义

默认安装中的默认架构称为public,其中创建了所有不合格的对象。所以在你的情况下,你很可能想要使用它。

由于两个表名称相同,因此您还需要为每个表使用表别名以便能够区分它们。

select  *
from bar.foo bf
  join public.foo pf on pf.id = bf.id
where bf.baz = 'test'

【讨论】:

  • 正是我想要的!用public 替换上面示例中的root_schema 效果很好:)
猜你喜欢
  • 1970-01-01
  • 2016-07-07
  • 1970-01-01
  • 2011-04-22
  • 2011-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多