首页 > 解决方案 > 为什么约束不在公共模式中不可见?

问题描述

我正在架构中创建一个具有唯一索引的表,如下所示:

create schema s1;
create table s1.test(key int);
create unique index test_index on s1.test(key);

现在,当我查询时information_schema.table_constraints,未显示索引。这是为什么?但是,索引正常工作:

test=# insert into s1.test(key) values (1);
INSERT 0 1
test=# insert into s1.test(key) values (1);
ERROR:  duplicate key value violates unique constraint "test_index"
DETAIL:  Key (key)=(1) already exists.

test我在这里使用的数据库归当前用户所有。

更新

看起来约束也没有显示在public模式中:

create table test(key int);
create unique index test_index on test(key);
select * from information_schema.table_constraints;

标签: postgresql

解决方案


现在,当我查询 information_schema.table_constraints 时,没有显示索引

UNIQUE INDEX!=CONSTRAINT您需要添加CONSTRAINT

ALTER TABLE test ADD CONSTRAINT uq_test_key UNIQUE(key);

-- constraint info
SELECT *
FROM information_schema.table_constraints;


-- supportive index info
select
 t.relname as table_name,
 i.relname as index_name,
 a.attname as column_name
from
 pg_class t,
 pg_class i,
 pg_index ix,
 pg_attribute a
where
 t.oid = ix.indrelid
 and i.oid = ix.indexrelid
 and a.attrelid = t.oid
 and a.attnum = ANY(ix.indkey)
 and t.relkind = 'r'
 and t.relname = 'test';

DBFiddle Demo CONSTRAINT - 约束 + 索引

DBFiddle 演示仅索引 - 索引


推荐阅读