Postgresql查询库结构及表属性SQL总结
Posted 小妖云汐
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Postgresql查询库结构及表属性SQL总结相关的知识,希望对你有一定的参考价值。
Postgresql查询库结构及表属性
库结构(用户、表、序列、视图、触发器、物化视图)
- 【
用户
】 查询 数据库中的所有用户
-- 查询所有用户
select * from pg_user;
-- 查询当前用户
select * from current_user;
- 【
编码格式
】查询 所有数据库字符编码
show server_encoding
- 【
模式
】查询 数据库所有模式
SELECT schema_name FROM information_schema.schemata where schema_name not in
('pg_toast','pg_temp_1','pg_toast_temp_1','pg_catalog','information_schema')
- 【
表
】根据模式名 查询所有表
SELECT schemaname,tablename FROM pg_tables where schemaname='模式名'
- 【
序列
】 查询 序列
SELECT sequencename FROM pg_sequences WHERE schemaname = '模式名'
- 【
视图
】根据用户名 查询所有视图
SELECT viewname FROM pg_views WHERE schemaname= '模式名'
- 【
触发器
】根据用户名 查询所有触发器
SELECT TRIGGER_NAME,event_object_table,action_statement FROM information_schema.TRIGGERS
WHERE TRIGGER_SCHEMA='模式名'
- 【
物化视图
】根据用户名 查询所有物化视图
select matviewname from pg_matviews WHERE schemaname ='模式名'
表属性(字段、主键、外键、索引、唯一约束)
- 【
字段
】根据表名 查询 列属性
-- 查询字段属性
select ordinal_position column_id,COLUMN_NAME,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH data_length,
IS_NULLABLE nullable,null pk_column
from information_schema.columns where table_schema='模式名' and table_name='表名'
-- 查询字段注释
SELECT c.relname as tablename ,a.attname as cols,col_description(a.attrelid,a.attnum)
FROM pg_class as c,pg_attribute as a ,pg_tables as b
where a.attrelid = c.oid and a.attnum>0 and c.relname=b.tablename
and b.schemaname='模式名' and c.relname = '表名'
- 【
主键
】根据表名 查询 主键
SELECT distinct kcu.column_name FROM information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name
WHERE constraint_type = 'PRIMARY KEY'
AND tc.table_name = '表名' and tc.constraint_schema='模式名'
- 【
外键
】根据表名 查询 外键 及 外键关联的详细信息
SELECT tc.constraint_name, tc.table_name, kcu.column_name,
ccu.table_name AS foreign_table_name,ccu.column_name AS foreign_column_name
FROM information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name
JOIN information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY'
AND tc.table_name = '表名' and tc.constraint_schema='模式名'
- 【
索引
】根据表名 查询 索引
select indexname,indexdef from pg_indexes
where tablename='表名' and schemaname = '模式名'
and indexname not in(SELECT distinct constraint_name FROM information_schema.table_constraints
WHERE table_name = '表名' and constraint_schema='模式名')
- 【
唯一约束
】根据表名 查询 唯一约束
SELECT distinct tc.constraint_name,kcu.column_name FROM information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu ON tc.constraint_name = kcu.constraint_name
WHERE constraint_type = 'UNIQUE'
AND tc.table_name = '表名' and tc.constraint_schema='模式名'
以上是关于Postgresql查询库结构及表属性SQL总结的主要内容,如果未能解决你的问题,请参考以下文章
mysql优化之sql执行流程及表结构(schema)对性能的影响