我知道可以使用\d命令列出模式。 然而,我需要制作一个前端应用程序来显示表的属性名称。如何仅从PostgreSQL中获取属性名称?
谢谢!
我知道可以使用\d命令列出模式。 然而,我需要制作一个前端应用程序来显示表的属性名称。如何仅从PostgreSQL中获取属性名称?
谢谢!
您需要查询 pg_catalog
或 information_schema
模式下的适当表格。
运行 psql -E ...
命令,然后 psql 显示内部命令中使用的元数据查询,例如 \d, \dt, \dv, ...
information_schema
与 pg_catalog
相同,但更加便携(它在 SQL 标准中定义)。如果您的应用程序仅使用 postgres,则建议使用 pg_catalog
而不是 information_schema
例如,此查询显示 attribute
的列
SELECT a.attname,
pg_catalog.format_type(a.atttypid, a.atttypmod),
(SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)
FROM pg_catalog.pg_attrdef d
WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef),
a.attnotnull, a.attnum
FROM pg_catalog.pg_attribute a
WHERE a.attrelid = 'attribute'::regclass AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum
SELECT attname
FROM pg_catalog.pg_attribute
WHERE attrelid = 'attribute'::regclass AND attnum > 0 AND NOT attisdropped
或使用等效查询:
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'attribute'
ORDER BY ordinal_position
如果您在多个模式中具有相同名称的表,则需要使用模式名称,并且查询会稍微复杂一些。
attribute
是我的示例表名 :). 错误信息是什么?这是来自Postgres 8.4 - 可能是一些复制和粘贴格式问题。如果您有一个名为 'my_table' 的表,则使用... WHERE a.attrelid ='my_table':: regclass AND ...
- mys