我如何从postgres表中获得特定字段的数据类型? 例如 我有下面的表格, student_details ( stu_id整数, Stu_name varchar(30), joined_date时间戳 );

在此使用字段名/或任何其他方式,我需要获得特定字段的数据类型。有可能吗?


当前回答

如果你喜欢“Mike Sherrill”的解决方案,但不想使用psql,我使用这个查询来获取缺失的信息:

select column_name,
case 
    when domain_name is not null then domain_name
    when data_type='character varying' THEN 'varchar('||character_maximum_length||')'
    when data_type='numeric' THEN 'numeric('||numeric_precision||','||numeric_scale||')'
    else data_type
end as myType
from information_schema.columns
where table_name='test'

与结果:

column_name |     myType
-------------+-------------------
 test_id     | test_domain
 test_vc     | varchar(15)
 test_n      | numeric(15,3)
 big_n       | bigint
 ip_addr     | inet

其他回答

试试这个请求:

SELECT column_name, data_type FROM information_schema.columns WHERE 
table_name = 'YOUR_TABLE' AND column_name = 'YOUR_FIELD';

https://www.postgresql.org/docs/current/app-psql.html#APP-PSQL-PATTERNS

\gdesc显示描述(即列名和数据) 类型)当前查询缓冲区的结果。查询不是 实际执行;但是,如果它包含某种类型的语法错误, 该错误将以正常方式报告。 如果当前查询缓冲区为空,则最近发送的查询为 描述。

所以你可以table student_details limit 0 \gdesc 输出占用的空间小于\d

你可以从information_schema中获取数据类型(这里引用了8.4文档,但这不是一个新特性):

=# select column_name, data_type from information_schema.columns
-# where table_name = 'config';
    column_name     | data_type 
--------------------+-----------
 id                 | integer
 default_printer_id | integer
 master_host_enable | boolean
(3 rows)

从information_schema提取数据类型是可能的,但不方便(需要用case语句连接几个列)。或者也可以使用format_type内置函数来实现这一点,但它适用于在pg_attribute中可见但在information_schema中不可见的内部类型标识符。例子

SELECT a.attname as column_name, format_type(a.atttypid, a.atttypmod) AS data_type
FROM pg_attribute a JOIN pg_class b ON a.attrelid = b.relfilenode
WHERE a.attnum > 0 -- hide internal columns
AND NOT a.attisdropped -- hide deleted columns
AND b.oid = 'my_table'::regclass::oid; -- example way to find pg_class entry for a table

基于https://gis.stackexchange.com/a/97834。

如果你喜欢“Mike Sherrill”的解决方案,但不想使用psql,我使用这个查询来获取缺失的信息:

select column_name,
case 
    when domain_name is not null then domain_name
    when data_type='character varying' THEN 'varchar('||character_maximum_length||')'
    when data_type='numeric' THEN 'numeric('||numeric_precision||','||numeric_scale||')'
    else data_type
end as myType
from information_schema.columns
where table_name='test'

与结果:

column_name |     myType
-------------+-------------------
 test_id     | test_domain
 test_vc     | varchar(15)
 test_n      | numeric(15,3)
 big_n       | bigint
 ip_addr     | inet