SELECT * FROM (
SELECT
pgc.contype as constraint_type,
pgc.conname as constraint_name,
ccu.table_schema AS table_schema,
kcu.table_name as table_name,
CASE WHEN (pgc.contype = 'f') THEN kcu.COLUMN_NAME ELSE ccu.COLUMN_NAME END as column_name,
CASE WHEN (pgc.contype = 'f') THEN ccu.TABLE_NAME ELSE (null) END as reference_table,
CASE WHEN (pgc.contype = 'f') THEN ccu.COLUMN_NAME ELSE (null) END as reference_col,
CASE WHEN (pgc.contype = 'p') THEN 'yes' ELSE 'no' END as auto_inc,
CASE WHEN (pgc.contype = 'p') THEN 'NO' ELSE 'YES' END as is_nullable,
'integer' as data_type,
'0' as numeric_scale,
'32' as numeric_precision
FROM
pg_constraint AS pgc
JOIN pg_namespace nsp ON nsp.oid = pgc.connamespace
JOIN pg_class cls ON pgc.conrelid = cls.oid
JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = pgc.conname
LEFT JOIN information_schema.constraint_column_usage ccu ON pgc.conname = ccu.CONSTRAINT_NAME
AND nsp.nspname = ccu.CONSTRAINT_SCHEMA
UNION
SELECT null as constraint_type , null as constraint_name , 'public' as "table_schema" ,
table_name , column_name, null as refrence_table , null as refrence_col , 'no' as auto_inc ,
is_nullable , data_type, numeric_scale , numeric_precision
FROM information_schema.columns cols
Where 1=1
AND table_schema = 'public'
and column_name not in(
SELECT CASE WHEN (pgc.contype = 'f') THEN kcu.COLUMN_NAME ELSE kcu.COLUMN_NAME END
FROM
pg_constraint AS pgc
JOIN pg_namespace nsp ON nsp.oid = pgc.connamespace
JOIN pg_class cls ON pgc.conrelid = cls.oid
JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = pgc.conname
LEFT JOIN information_schema.constraint_column_usage ccu ON pgc.conname = ccu.CONSTRAINT_NAME
AND nsp.nspname = ccu.CONSTRAINT_SCHEMA
)
) as foo
ORDER BY table_name desc
select pgc.conname as constraint_name,
ccu.table_schema as table_schema,
ccu.table_name,
ccu.column_name,
contype,
pg_get_constraintdef(pgc.oid)
from pg_constraint pgc
join pg_namespace nsp on nsp.oid = pgc.connamespace
join pg_class cls on pgc.conrelid = cls.oid
left join information_schema.constraint_column_usage ccu
on pgc.conname = ccu.constraint_name
and nsp.nspname = ccu.constraint_schema
order by pgc.conname;
4条答案
按热度按时间avwztpqn1#
可以使用
SELECT
查询从catalog-pg-constraint.检索表的约束。并且同样可以在
PSQL
中使用xj3cbfub2#
这是POSTGRES特定的答案**.....它将检索所有列及其关系**
pieyvz9o3#
我没能让上面的解决方案工作。也许它们不再被支持,或者更可能是我做错了什么。这就是我如何让它工作的。注意,“contype”列将缩写为约束类型(例如,'c'为检查,'p'为主键,等等)。我包括该变量,以防你想添加一个WHERE语句来过滤它之后的FROM块。
esyap4oy4#
SELECT约束名,表名,列名,序号位置FROM信息模式.键列用法WHERE table_name = '在此处输入表名';