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='模式名'