gpt4 book ai didi

SQL : unique values across two columns

转载 作者:行者123 更新时间:2023-12-04 03:22:10 24 4
gpt4 key购买 nike

考虑到两列,是否存在对值不唯一的约束,例如 -

id  |  secondid
+---------------+
3 | 4
4 | 5

id | secondid
+---------------+
3 | 4
5 | 4

id | secondid
+---------------+
4 | 4
4 | 4

以上所有情况都不对,因为 4 在 idsecondid 中出现了两次,但类似的东西

id  |  secondid
+---------------+
1 | 3
2 | 4

没关系,因为两列中的所有值都是唯一的,我有没有办法在不使用 postgresql 中的任何包的情况下实现这一点?

最佳答案

您可以结合使用排除约束和检查约束来做到这一点。需要检查约束以防止一行内出现重复。

create table t (
id int,
id2 int,
check (id <> id2),
exclude using gist ( (array[id, id2]) with &&)
);

exclusion constraint通过检查指定的运算符从不为"new"行中的列和表中已有的所有行返回“true”来进行操作。它不检查当前行中的值,这就是为什么还需要 check 约束。

Here是一个数据库<> fiddle 。

关于SQL : unique values across two columns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68325215/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com