微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

“唯一”约束的奇怪情况排除的可能情况| Postgres

如何解决“唯一”约束的奇怪情况排除的可能情况| Postgres

我有一个关于约束的问题(我猜在这种情况下是唯一的或排除的)。我无法理解这个简单的案例:

例如我有一个表格的简化版本:

create table user
(
    id                            serial                   not null
    username                      varchar(30)              not null
        constraint user_username_key
            unique,is_active                     boolean                  not null,company_id                    integer                  not null
       constraint company_user_company_company_company_id
    references company_company
    deferrable initially deferred

我想创建这样的约束来满足以下条件:

如果我们至少有一条(或可能的几条记录)引用相同的 company_id(假设 = 3),我们必须(它应该存在)有一个和只有一个以“-support”(假设为“user1-support”)结尾且带有 is_active = True用户名

错误的场景:

• we have one or more records but there are no  any username that ends on `‘-support’` amoung this records
• we have one or more records and we have multiple  usernames that ends on `‘-support’` amoung this records

如果我们只有一个条目 - 那么用户名应该以 ‘-support’ 结尾

谢谢

对不起,如果问题很幼稚

postgres 11 版本

解决方法

可以使用过滤的唯一索引:

CREATE UNIQUE INDEX idx ON "user"
  (company_id,(CASE WHEN username LIKE '%-support' THEN 'support' ELSE username END)) 
WHERE is_Active = True;

db<>fiddle demo

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。