Postgres9.0支持排除约束,这有点像通用的唯一约束(http://www.postgresql.org/docs/9.0/static/sql-createtable.html#SQL-CREATETABLE-EXCLUDE)。
我认为这可能是解决这个问题的好方法,但我不知道如何正确使用排除约束。
问题是:我有一个这样的表:
CREATE TABLE emails (
id integer NOT NULL,
email character varying(255),
"primary" boolean DEFAULT false,
user_id integer,
);我希望确保每个唯一的user_id只有一行的"primary"等于true。我尝试使用如下的排除约束:
ALTER TABLE emails ADD CONSTRAINT one_primary_email_per_user EXCLUDE USING gist (user_id WITH =, "primary" WITH &);Postgres拒绝了这一点:
ERROR: data type boolean has no default operator class for access method "gist"
HINT: You must specify an operator class for the index or define a default operator class for the data type.我再次尝试将布尔列转换为bit
ALTER TABLE emails ADD CONSTRAINT one_primary_email_per_user EXCLUDE (user_id WITH =, (case "primary" when 't' then '1'::bit else '0'::bit end) WITH &);这不管用。似乎&(bit,bit)不是运算符类bit_ops的一部分
ERROR: operator &(bit,bit) is not a member of operator family "bit_ops"
DETAIL: The exclusion operator must be related to the index operator class for the constraint.看看http://www.leadum.com/downloads/dbscribe/samples/postgresql/web_modern/opclass/main/790197862.html,bit_ops似乎只包括排序比较运算符(>、<、=、>=、<=),而不包括按位运算符。我不太确定为什么会这样。
使用排除约束时,这种排除是可能的吗?有没有更好的方法来做这件事?
谢谢你的帮助!
发布于 2013-06-20 22:20:38
为此创建部分唯一索引应该更简单:
create unique index on emails(email) where (primary);(与此答案正交,但由于您询问的是错误消息:对于排除约束,您可能希望添加btree_gin或btree_gist扩展以与btree运算符一起使用。)
https://stackoverflow.com/questions/17215708
复制相似问题