我可以从数据类型中选择一个字段吗?

问题描述 投票:0回答:2

我可以从数据类型中选择字段/列吗?

Postgres 7.4(是的,我们正在升级)

SELECT *
FROM tbl_name
WHERE tbl_name.column = 'timestamp with time zone'
sql postgresql sqldatatypes
2个回答
3
投票

这需要元数据。

select column_name
from information_schema.columns
where table_schema='your_schema'
and table_name='tbl_name'
and data_type='timestamp without time zone'
order by ordinal_position;

ETA:如果你想要来自表的实际数据,其列名与上面的列表匹配,你可以设置一个用户定义的函数来获取这些列名,将它们放在逗号分隔的列表中,然后解析查询从 tbl_name 适当地(当然,如果你在数据库之外使用脚本语言,这会容易得多)。


1
投票

我最近不得不这样做。为了简化事情,我定义了两个视图:

CREATE  VIEW view_table_columns AS 
 SELECT n.nspname AS schema, cl.relname AS table_name, 
  a.attname AS column_name, ty.typname AS data_type, 
  a.attnotnull AS nnull, 
  a.atthasdef AS hasdef, 
  descr.description AS descr, cl.oid AS tableoid, a.attnum AS colnum
   FROM pg_attribute a
   JOIN pg_class cl ON a.attrelid = cl.oid AND cl.relkind = 'r'::"char"
   JOIN pg_namespace n ON n.oid = cl.relnamespace
   JOIN pg_type ty ON ty.oid = a.atttypid
   LEFT JOIN pg_description descr 
       ON descr.objoid = cl.oid AND descr.objsubid = a.attnum
   WHERE a.attnum > 0 AND NOT a.attisdropped 
       AND n.nspname !~~ 'pg_%'::text 
       AND n.nspname <> 'information_schema'::name;

COMMENT ON VIEW view_table_columns IS 'Lista all fields of all tables';


CREATE VIEW view_table_columns2 AS 
 SELECT view_table_columns.*, 
 ( SELECT count(*) AS count
      FROM pg_index
      WHERE pg_index.indrelid = pg_index.tableoid AND 
  (view_table_columns.colnum = ANY   (pg_index.indkey::smallint[]))) AS indexes
   FROM view_table_columns;

COMMENT ON VIEW view_table_columns2 IS 'Adds to view_table_columns info about indexed fields';

对于表格中的每个字段,包括以下信息:

  • 架构名称
  • 桌名
  • 栏目名称
  • 数据类型名称
  • 可以为空吗?
  • 有默认值吗?
  • 描述(评论)
  • tableoid(如果您需要从目录中获取更多数据则很方便)
  • 列号(同上)
  • indexes(在第二个视图中 - 引用此列的索引数)
© www.soinside.com 2019 - 2024. All rights reserved.