gpt4 book ai didi

Postgresql 强制列的唯一双向组合

转载 作者:行者123 更新时间:2023-11-29 11:26:14 25 4
gpt4 key购买 nike

我正在尝试创建一个表,该表将在两个方向上强制执行相同类型的两列的唯一组合。例如。这是非法的:

col1 col2
1 2
2 1

我想出了这个,但它不起作用:

database=> \d+ friend;
Table "public.friend"
Column | Type | Modifiers | Storage | Stats target | Description
--------------+--------------------------+-----------+----------+--------------+-------------
user_id_from | text | not null | extended | |
user_id_to | text | not null | extended | |
status | text | not null | extended | |
sent | timestamp with time zone | not null | plain | |
updated | timestamp with time zone | | plain | |
Indexes:
"friend_pkey" PRIMARY KEY, btree (user_id_from, user_id_to)
"friend_user_id_to_user_id_from_key" UNIQUE CONSTRAINT, btree (user_id_to, user_id_from)
Foreign-key constraints:
"friend_status_fkey" FOREIGN KEY (status) REFERENCES friend_status(name)
"friend_user_id_from_fkey" FOREIGN KEY (user_id_from) REFERENCES user_account(login)
"friend_user_id_to_fkey" FOREIGN KEY (user_id_to) REFERENCES user_account(login)
Has OIDs: no

是否可以在没有触发器或任何高级魔法的情况下仅使用约束来编写此代码?

最佳答案

不需要扩展的 Neil 解决方案的变体是:

create table friendz (
from_id int,
to_id int
);

create unique index ifriendz on friendz(greatest(from_id,to_id), least(from_id,to_id));

不过,Neil 的解决方案允许您使用任意数量的列。

我们都依赖于使用表达式来构建记录在案的索引 https://www.postgresql.org/docs/current/indexes-expressional.html

关于Postgresql 强制列的唯一双向组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30036837/

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