给定表名,从pg数据库读取该表所在模式、字段信息、表注释、主键和唯一索引等信息
时间: 2023-07-31 22:11:01 浏览: 142
获取oracle 表字段,表名,以及主键之类等等的信息
5星 · 资源好评率100%
可以使用以下 SQL 语句从 PostgreSQL 数据库中获取表的相关信息:
```sql
SELECT
ns.nspname AS schema_name,
cls.relname AS table_name,
col.column_name AS column_name,
col.data_type AS data_type,
col.column_default AS column_default,
col.is_nullable AS is_nullable,
com.description AS table_comment,
cons.constraint_type AS constraint_type,
array_to_string(array_agg(DISTINCT clu.column_name), ',') AS primary_keys,
array_to_string(array_agg(DISTINCT idx.index_name), ',') AS unique_indexes
FROM
pg_catalog.pg_namespace ns
INNER JOIN pg_catalog.pg_class cls ON cls.relnamespace = ns.oid
INNER JOIN pg_catalog.pg_attribute col ON col.attrelid = cls.oid
LEFT JOIN pg_catalog.pg_description com ON (cls.oid = com.objoid AND com.objsubid = 0)
LEFT JOIN pg_catalog.pg_constraint cons ON cons.conrelid = cls.oid
LEFT JOIN information_schema.constraint_column_usage clu ON clu.constraint_name = cons.constraint_name
LEFT JOIN (
SELECT
indrelid::regclass AS table_name,
indexrelid::regclass AS index_name,
indkey,
indisunique
FROM
pg_index
) idx ON idx.table_name = cls.relname AND idx.indisunique = TRUE AND col.attnum = ANY(idx.indkey)
WHERE
ns.nspname = 'schema_name'
AND cls.relname = 'table_name'
AND col.attnum > 0
GROUP BY
ns.nspname,
cls.relname,
col.column_name,
col.data_type,
col.column_default,
col.is_nullable,
com.description,
cons.constraint_type;
```
其中,需要将 `schema_name` 和 `table_name` 替换为对应的模式名和表名。执行该语句后,会返回一个结果集,包含以下字段:
- `schema_name`:表所在模式名
- `table_name`:表名
- `column_name`:字段名
- `data_type`:数据类型
- `column_default`:默认值
- `is_nullable`:是否可为空(YES 或 NO)
- `table_comment`:表注释
- `constraint_type`:约束类型(如 PRIMARY KEY、UNIQUE 等)
- `primary_keys`:主键字段名,多个字段用逗号分隔
- `unique_indexes`:唯一索引名,多个索引用逗号分隔
需要注意的是,该语句中使用了 PostgreSQL 的系统表和视图,因此需要确保连接的数据库用户具有访问这些表和视图的权限。
阅读全文