Postgres 数组的唯一约束
如何对数组中所有值的唯一性创建约束,例如:
CREATE TABLE mytable
(
interface integer[2],
CONSTRAINT link_check UNIQUE (sort(interface))
)
我需要的排序函数
create or replace function sort(anyarray)
returns anyarray as $$
select array(select $1[i] from generate_series(array_lower($1,1),
array_upper($1,1)) g(i) order by 1)
$$ language sql strict immutable;
将值 {10, 22} 和 {22, 10} 视为相同,并在唯一约束下进行检查
How to create a constraint on the uniqueness of all the values in the array like:
CREATE TABLE mytable
(
interface integer[2],
CONSTRAINT link_check UNIQUE (sort(interface))
)
my sort function
create or replace function sort(anyarray)
returns anyarray as $
select array(select $1[i] from generate_series(array_lower($1,1),
array_upper($1,1)) g(i) order by 1)
$ language sql strict immutable;
I need that would be the value {10, 22} and {22, 10} considered the same and check under the UNIQUE CONSTRAINT
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您不能使用带有唯一约束<的函数/a> 但你可以使用唯一索引 。因此,给定一个类似这样的排序函数:
那么你可以这样做:
然后会发生以下情况:
I don't think you can use a function with a unique constraint but you can with a unique index. So given a sorting function something like this:
Then you could do this:
Then the following happens:
mu 已经演示了 表达式索引 可以解决您的问题。
我的注意力被使用的功能吸引了。对于两个整数的数组来说,这两种方法似乎都太过分了。这可能是真实情况的简化?不管怎样,我很感兴趣,并用几个变体进行了测试。
测试设置
包含 10000 个随机整数对的临时表:
用简短的注释来解释每个候选者的测试:
ORDER BY
相同(第 9.0 页+)int[]
array_lower()
- it始终为 1STRICT
修饰符 (!)结果
我执行了大约 20 次,并从
EXPLAIN ANALYZE
中获得了最佳结果。这些是 Debian Squeeze 上 v9.0.5 服务器的结果。 v.8.4 上的结果类似。
我还测试了 PL/pgSQL 变体,它们比预期慢一些:对于一个微小的操作来说开销太大,没有查询计划可以缓存。
简单函数(nr. 7)比其他函数快得多。这是预料之中的,其他变体的开销对于小型数组来说太大了。
忽略
STRICT
声明可以使速度加倍以上。我没想到这一点,并发布了这个后续文章来揭示原因:mu already demonstrated how an index on an expression can solve your problem.
My attention was caught by the used functions. Both seem like overkill for arrays of two integers. This may be a simplification of the real situation? Either way, I was intrigued and ran a test with a couple of variants.
Test setup
Temporary table with 10000 random pairs of integer:
Test candidates with a short comment to explain each one:
ORDER BY
inside aggregate (pg 9.0+)int[]
array_lower()
- it is always 1STRICT
modifier (!)Results
I executed each around 20 times and took the best result from
EXPLAIN ANALYZE
.These are the results from a v9.0.5 server on Debian Squeeze. Similar results on v.8.4.
I also tested PL/pgSQL variants which were a bit slower as expected: too much overhead for a tiny operation, no query plan to cache.
The simple function (nr. 7) is substantially faster than the others. That was expected, the overhead of the other variants is just too much for a tiny array.
Leaving away the
STRICT
declaration more than doubles the speed. I did not expect that and posted this follow-up uncover why:只需在两个值上创建唯一索引:
Just create a unique index on the two values: