hstore键的唯一索引或约束 [英] unique index or constraint on hstore key
问题描述
我想在hstore列中的特定键上创建唯一索引或约束(如果存在)。我希望在另一个问题中找到答案:
但是我尝试了我能想到的每个语法版本
当前,我的表是
hstore_table
hstore字段是hstore_value
,我想强制使其唯一的键是'foo'和'bar'(当它们存在时)。 / p>
我的PostgreSQL版本是8.4.13
如果我ve正确理解了您的要求后,想要一个局部唯一的功能索引:
CREATE TABLE hstest(x hstore not null );
创建唯一索引hstest_key_k1_values_unique
在hstest((x->'k1'))
WHERE(x?'k1');
不是严格要求 WHERE
子句因为如果没有找到,键查找将为null。
如果要使用多个键,请使用两个索引(如果希望两个键是独立的),或者如果要对两个表达式进行索引链接它们,以便唯一约束允许(1,2)和(1,3)或(2,2),但不允许另一个(1,2),例如:
创建唯一索引hstest_key_k1k2_values_unique
在hstest上((x->'k1'),(x->'k2'));
I would like to create a unique index or constraint on a specific keys in an hstore column if that key exists. I was hoping the answer would be found somewhere in this other question:
Practical limitations of expression indexes in PostgreSQL
But I tried every version of the syntax I could come up with and nothing would work.
currently, my table is
hstore_table
the hstore field is hstore_value
and they keys I would like to force to be unique are 'foo' and 'bar' when they exist.
My version of PostgreSQL is 8.4.13
If I've understood what you're asking for correctly, you want a partial unique functional index:
CREATE TABLE hstest ( x hstore not null );
CREATE UNIQUE INDEX hstest_key_k1_values_unique
ON hstest((x -> 'k1'))
WHERE ( x ? 'k1' );
The WHERE
clause isn't strictly required as the key lookup will be null if it's not found. Whether it's appropriate will depend on your queries.
If you want multiple keys, use two indexes if you want the two to be independent, or index two expressions if you want to link them so the unique constraint allows (1,2) and (1,3) or (2,2) but not another (1,2), like this:
CREATE UNIQUE INDEX hstest_key_k1k2_values_unique
ON hstest ((x -> 'k1'), (x -> 'k2'));
这篇关于hstore键的唯一索引或约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!