简体   繁体   English

唯一约束不起作用? (PostgreSQL)

[英]UNIQUE Constraint not working? (Postgresql)

I altered my postgresql database table to have a unique constraint like this:我更改了我的 postgresql 数据库表,使其具有这样的唯一约束:

ALTER TABLE my_table
ADD CONSTRAINT unique_values UNIQUE (value_one, value_two, value_three);

I want to not be able to post duplicate values for value_one, value_two, or value_three.我希望不能发布 value_one、value_two 或 value_three 的重复值。 So there should only ever be ONE unique value in these columns in the entire database.因此,整个数据库中的这些列中应该只有一个唯一值。

But I'm still able to INSERT duplicate values in the value_one, value_two, and value_three columns.但我仍然可以在 value_one、value_two 和 value_three 列中插入重复值。

What am I doing wrong?我究竟做错了什么?

Edit:编辑:

I have deleted all the duplicate data in the database, but get an error whenever I try to add a unique constraint to individual columns in the table.我已删除数据库中的所有重复数据,但每当我尝试向表中的各个列添加唯一约束时都会出错。

Another thing, if I say:另一件事,如果我说:

ALTER TABLE my_table
ADD CONSTRAINT unique_values UNIQUE (value_one, value_two, value_three);

I do not get an error.我没有收到错误。 But if I say:但如果我说:

ALTER TABLE my_table
ADD CONSTRAINT unique_values UNIQUE (value_one);

Like with just one value, I get this error:就像只有一个值一样,我收到此错误:

could not create unique index "unique_values"

If you define a unique constraint over three columns, that means that you cannot insert the same three values a second time.如果您在三列上定义唯一约束,则意味着您不能再次插入相同的三个值。 But each of these columns can contain duplicate values.但是这些列中的每一列都可以包含重复值。 For example, these three rows would satisfy the uniqueness constraint:例如,这三行将满足唯一性约束:

(1, 2, 3)
(1, 2, 4)
(1, 5, 3)

but you would get an error if you inserted one of these triples a second time.但是如果你第二次插入这些三元组之一,你会得到一个错误。

If you want each column to be unique, you have to define three constraints, one for each column.如果您希望每一列都是唯一的,则必须定义三个约束,每列一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM