在PSQL中更改唯一约束

时间:2018-12-31 08:49:33

标签: sql postgresql ddl

我有一个称为地址的表,在两个字段上具有唯一约束:(地址和主机名)。我意识到我需要再添加1个字段到约束中。我有一排需要插入相同的地址和主机名,但没有coin_id。尝试插入时,我得到了。

ERROR:  duplicate key value violates unique constraint "address_uniq"
DETAIL:  Key (address, hostname)=(GfFrqCJtwuSSJyv6D1STtrT146N8p9cLtd, NHWithdrawal) already exists.
SQL state: 23505

我尝试使用以下方法查看约束:

select * from information_schema.table_constraints
where constraint_type = 'UNIQUE'

我在该列表中看不到address_uniq约束。

如何执行以下操作:

  1. 使用psql查找此约束
  2. 更改/更新此约束,并向其添加1列

2 个答案:

答案 0 :(得分:1)

  

[我如何使用psql找到此约束

如果我们违反主键约束,我们会得到相同的错误消息。

# alter table addresses add constraint addresses_pk primary key (id);
ALTER TABLE
# insert into addresses values (1, 2, 4, 4);
ERROR:  duplicate key value violates unique constraint "addresses_pk"
DETAIL:  Key (id)=(1) already exists.
# 

尝试搜索信息模式where constraint_type = 'PRIMARY KEY'

请注意,我们不必命名主键约束,因为Postgres会生成默认值<table_name>_pkey。因此,要在您的情况下将此作为解决方案,就意味着创建主键的人都会为其指定一个明确的名称address_uniq,这会造成混淆。

因此,更有可能的是您在这些列上具有唯一索引。索引不会显示在信息模式中。您可以像这样检查:

select * from pg_indexes where tablename = 'addresses';
  

[我如何]更改/更新此约束,并向其添加1列

如果您的问题是索引,请执行以下操作:

# drop index address_uniq;
DROP INDEX
# create unique index address_uniq on addresses (address, hostname, coin_id);
CREATE INDEX
# 

如果发现这是一个主键约束,则它是一个类似的过程:

# alter table addresses drop constraint address_uniq;
ALTER TABLE
# alter table addresses add constraint address_uniq primary key (address, hostname,coin_id);
ALTER TABLE
# 

答案 1 :(得分:0)

您的constraint_type也应为“ PRIMARY KEY”,以便找到最佳方式 约束正在使用constraint_name。

select * from information_schema.table_constraints where constraint_name = 'address_uniq'

您可以删除现有约束

ALTER TABLE your_table_name DROP CONSTRAINT address_uniq;

并添加一个新的

ALTER TABLE your_table_name ADD CONSTRAINT address_uniq PRIMARY KEY(address, hostname, coin_id);

ALTER TABLE your_table_name ADD CONSTRAINT address_uniq UNIQUE(address, hostname, coin_id);