跨多个列的排列的唯一postgres约束 [英] Unique postgres constraint for permutations across multiple columns

查看:222
本文介绍了跨多个列的排列的唯一postgres约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Postgres数据库中给出以下三列:first,second,third;如何创建一个约束,使排列是唯一的?



例如。如果db,('bar','shiz','foo')中存在('foo','bar','shiz')将被排除为非唯一索引。

解决方案

您可以使用hstore创建唯一索引:

  CREATE UNIQUE INDEX hidx ON test使用BTREE(hstore(ARRAY [a,b,c],ARRAY [a,b ,C])); 

小提琴



UPDATE



其实



CREATE UNIQUE INDEX hidx ON test使用BTREE(hstore(ARRAY [a,b,c],ARRAY [null,null,null]))

可能是一个更好的主意,因为它将工作相同,但应占用更少的空间(小提示)。


Given the following three columns in a Postgres database: first, second, third; how can I create a constraint such that permutations are unique?

E.g. If ('foo', 'bar', 'shiz') exist in the db, ('bar', 'shiz', 'foo') would be excluded as non-unique.

解决方案

You could use hstore to create the unique index:

CREATE UNIQUE INDEX hidx ON test USING BTREE (hstore(ARRAY[a,b,c], ARRAY[a,b,c]));

Fiddle

UPDATE

Actually

CREATE UNIQUE INDEX hidx ON test USING BTREE (hstore(ARRAY[a,b,c], ARRAY[null,null,null]));

might be a better idea since it will work the same but should take less space (fiddle).

这篇关于跨多个列的排列的唯一postgres约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆