在PostgreSQL中,我具有以下表定义
create table file(
file_id int generated by default as identity primary key,
file_name text UNIQUE not null
);
我的问题是:如何删除file_name
上的唯一约束?
答案 0 :(得分:4)
对于这种约束,Postgres使用的默认命名策略是tablename_columnname_key
,因此您的情况将是file_file_name_key
因此您可以使用
alter table file drop constraint file_file_name_key;
如果您不想依赖默认的命名策略,则可以使用以下查询来检索名称:
select constraint_name
from information_schema.key_column_usage
where table_name = 'file'
and table_schema = 'public'
and column_name = 'file_name';
答案 1 :(得分:2)
您必须查询元数据(pg_constraint
,pg_index
,pg_attribute
)才能找到由列上的唯一索引实现的约束的名称。 / p>
PostgreSQL使用内部逻辑来自动生成名称(请参见其他答案),但是依靠它是脆弱的:如果该名称已经存在约束,PostgreSQL将通过附加数字来消除歧义。
答案 2 :(得分:1)
总是有任何约束的名称-只是如果您未指定Postgres或ORM(例如Hinernate)会自动生成一个约束。
如果您使用pgAdmin ,则只需单击该表,它将在描述中显示约束及其名称的列表:
对于上面的示例,我只需要运行:
ALTER Table word_pairs drop constraint word_pairs_foreign_word_key;
如果您不使用GUI ,则可以找到如下约束名称:
SELECT tc.constraint_name FROM information_schema.table_constraints
AS tc WHERE tc.constraint_type='UNIQUE'
AND tc.table_name='word_pairs';
(这是this answer的简化改编)