4

我知道我可以使用 \d 列出架构。但是,我需要制作一个前端应用程序来显示表的属性名称。如何在 PostgreSQL 中获取唯一的属性名称?

谢谢!

4

1 回答 1

5

您需要在pg_cataloginformation_schema模式下查询适当的表。运行psql -E ...,然后 psql 显示在内部命令中使用的元数据查询,例如\d, \dt, \dv, ...

information_schema与portalbe相同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

如果您在多个模式中具有相同名称的同一张表,则您还需要用户模式名称并且查询会稍微复杂一些。

于 2012-11-22T22:51:40.257 回答