我如何从postgres表中获得特定字段的数据类型? 例如 我有下面的表格, student_details ( stu_id整数, Stu_name varchar(30), joined_date时间戳 );
在此使用字段名/或任何其他方式,我需要获得特定字段的数据类型。有可能吗?
我如何从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
其他回答
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)
执行psql -E,然后执行\d student_details
可以使用pg_typeof()函数,该函数也适用于任意值。
SELECT pg_typeof("stu_id"), pg_typeof(100) from student_details limit 1;
如果你喜欢“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