如何在PostgreSQL中查找具有特定列的表

150

我正在使用PostgreSQL 9.1。我有一个表的列名。是否可以找到具有此列的表格?如果可以,如何操作?

6个回答

209

您也可以这样做。

 select table_name from information_schema.columns where column_name = 'your_column_name'

2
奇怪的是,我曾经看到过这个查询显示了@RomanPekar的查询没有显示的表格;我想知道为什么会这样。 - Ken Bellows
2
@KenBellows 我猜pg_class / pg_attribute可能会随着Postgresql的新版本而改变,而information_schema则在ANSI规范中定义。因此对于一般查询,我认为这个答案更好。有时候我需要对象ID,例如,在这种情况下,我需要使用特定于db引擎的表。此外,information_schema视图总是比db引擎特定的表多一个步骤,有时可能会导致(稍微)性能较差。 - Roman Pekar
1
这是两个解决方案中更准确的一个 - 在我的情况下。 pg_class 查询错过了 150 张表中的两张。 information_schema 查询捕获了所有表格。 我得查找一下为什么有两个表格不在联接范围之内。 无论如何,感谢您的信息! - Thomas Altfather Good

83

您可以查询系统目录

select c.relname
from pg_class as c
    inner join pg_attribute as a on a.attrelid = c.oid
where a.attname = <column name> and c.relkind = 'r'

sql fiddle demo


2
请注意,此查询似乎不接受“%”通配符,而Ravi答案中的查询则可以。 - Skippy le Grand Gourou
1
@SkippyleGrandGourou 它接受 "像'id%'" 的符号。 - jutky
1
这对我来说无论是否使用通配符都行不通,我不得不使用information.schema进行搜索。 - Lrawls

10

我以@Roman Pekar的查询为基础,并添加了模式名称(在我的情况下相关)。

select n.nspname as schema ,c.relname
    from pg_class as c
    inner join pg_attribute as a on a.attrelid = c.oid
    inner join pg_namespace as n on c.relnamespace = n.oid
where a.attname = 'id_number' and c.relkind = 'r'

sql fiddle 演示


5

简单来说:

$ psql mydatabase -c '\d *' | grep -B10 'mycolname'

如果需要,可以通过扩大-B偏移量来获取表名


这是一个相当巧妙的小快捷方式,不错。 - lacostenycoder

4

通配符支持 查找包含您要查找的字符串的表模式和表名称。

select t.table_schema,
       t.table_name
from information_schema.tables t
inner join information_schema.columns c on c.table_name = t.table_name
                                and c.table_schema = t.table_schema
where c.column_name like '%STRING%'
      and t.table_schema not in ('information_schema', 'pg_catalog')
      and t.table_type = 'BASE TABLE'
order by t.table_schema;

0
select t.table_schema,
       t.table_name
from information_schema.tables t
inner join information_schema.columns c on c.table_name = t.table_name 
                                and c.table_schema = t.table_schema
where c.column_name = 'name_colum'
      and t.table_schema not in ('information_schema', 'pg_catalog')
      and t.table_type = 'BASE TABLE'
order by t.table_schema;

6
编辑你的回答,为你的代码添加解释。该问题已经超过六年,并且已经有一个被接受的答案以及几个得到高票和良好解释的答案。如果你的回答没有这样的解释,它可能会被投票降低或删除。添加额外的信息可以帮助证明你的回答在这里继续存在的合理性。 - Das_Geek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接