PostgreSQL查询索引及字段详情(终极版)
with idx as (
select tc. relname as tablename , c. relname indexname , attr1. attname as field1, attr2. attname as field2, attr3. attname as field3, attr4. attname as field4, attr5. attname as field5, attr6. attname as field6, attr7. attname as field7from pg_index ileft join pg_class con i. indexrelid = c. oidleft join pg_class tcon i. indrelid = tc. oidleft join pg_attribute attr1on attr1. attrelid = tc. oidand attr1. attnum = i. indkey[ 0 ] left join pg_attribute attr2on attr2. attrelid = tc. oidand attr2. attnum = i. indkey[ 1 ] left join pg_attribute attr3on attr3. attrelid = tc. oidand attr3. attnum = i. indkey[ 2 ] left join pg_attribute attr4on attr4. attrelid = tc. oidand attr4. attnum = i. indkey[ 3 ] left join pg_attribute attr5on attr5. attrelid = tc. oidand attr5. attnum = i. indkey[ 4 ] left join pg_attribute attr6on attr6. attrelid = tc. oidand attr6. attnum = i. indkey[ 5 ] left join pg_attribute attr7on attr7. attrelid = tc. oidand attr7. attnum = i. indkey[ 6 ] where tc. relname not like '%act\_%' and not tc. relname ~ '[0-9]{4}$' and tc. relname not like '%\_other' and tc. relname not like '%\_others' and ( tc. relname like '%\_t' or tc. relname like '%\_ti' or tc. relname like '%\_tmp' ) and tc. relowner = ( select usesysid from pg_user where usename = CURRENT_SCHEMA) and indisunique = 't' and indisprimary = 'f' and c. relname not like '%\_pkey'
order by tablename, indexname
)
, idxs as (
select * from pg_indexeswhere schemaname = CURRENT_SCHEMAand indexdef like '%UNIQUE%' and tablename not like '%act\_%' and indexname not like '%\_pkey'
)
select idx. tablename, idx. indexname, idx. field1, idx. field2, idx. field3, idx. field4, idx. field5, idx. field6, idx. field7, case when position( ' WHERE ' in idxs. indexdef) > 0 then replace ( replace ( replace ( substring( idxs. indexdef from ( position( ' WHERE ' in idxs. indexdef) + 7 ) for length( idxs. indexdef) ) , '(' , '' ) , ')' , '' ) , '::text' , '' ) else null end as where_condition, idxs. indexdeffrom idxleft join idxson idx. indexname = idxs. indexname
;