gpt4 book ai didi

sql - postgresql 另一列的唯一索引

转载 作者:行者123 更新时间:2023-12-05 03:52:35 25 4
gpt4 key购买 nike

例如,我有这个表(postgresql):

CREATE TABLE t(
a TEXT,
b TEXT
);
CREATE UNIQUE INDEX t_a_uniq_idx ON t(a);

我想为 ba 列创建唯一约束/索引。但不是简单的 ADD CONSTRAINT t_ab UNIQUE (a, b)。我想要 a 的唯一 b:

INSERT INTO t(a,b) VALUES('123', null); -- this is ok
INSERT INTO t(a,b) VALUES('456', '123'); -- this is not ok, because duplicate '123'

我该怎么做?

编辑:

为什么我需要这个?例如,如果我有 users 表并且我想创建电子邮件更改功能,我需要这样的结构:

CREATE TABLE users(
email TEXT,
unconfirmed_email TEXT
-- some other data
);
CREATE UNIQUE INDEX unq_users_email_idx ON users(email);

用户可以将值设置到 unconfirmed_email 列中,但前提是该值未在 email 列中使用。

最佳答案

如果两个 列都需要唯一性,我认为您的数据模型有误。您应该有两个表,而不是将对存储在一行中:

create table pairs (
pairid int generated always as identity,
. . . -- more information about the pair, if needed
);

create table pairElements (
pairElementId int generated always as identity,
pairId int references pairs(pairid),
which int check (which in (1, 2)),
value text,
unique (pairid, which)
);

那么条件很简单:

create constraint unq_pairelements_value unique pairelements(value);

关于sql - postgresql 另一列的唯一索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62106582/

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