PostgreSQL中是否存在与Oracle column_id功能类似的对应字段?
对应字段说明
PostgreSQL 有两个和 Oracle all_tab_columns.column_id 功能完全一致的字段,用来标识列在表结构中的定义顺序:
- 信息标准视图
information_schema.columns中的ordinal_position字段,符合SQL标准,查询更简便 - 原生系统表
pg_attribute中的attnum字段,属于PostgreSQL底层元数据,适合进阶查询
常用查询示例
1. 基于信息模式的查询(推荐日常使用)
无需额外过滤,直接返回用户定义的有效列,排序逻辑和Oracle按column_id排序完全一致:
SELECT column_name, data_type, ordinal_position AS column_id FROM information_schema.columns WHERE table_schema = '你的表所在的模式名' -- 比如public AND table_name = '你要查询的表名' ORDER BY ordinal_position;
2. 基于原生系统表的查询
适合需要访问底层元数据的场景,需要手动过滤系统隐藏列和已删除的无效列:
SELECT attname AS column_name, format_type(atttypid, atttypmod) AS data_type, attnum AS column_id FROM pg_attribute WHERE attrelid = '模式名.表名'::regclass -- 比如public.test_table AND attnum > 0 -- 过滤掉ctid、xmin等系统内置列 AND NOT attisdropped -- 过滤掉已删除的列 ORDER BY attnum;
内容的提问来源于stack exchange,提问作者nivan283
相关产品推荐
相关产品推荐

