【问题标题】:How do you impose a case insensitive unique constraint on a Firebird field value?如何对 Firebird 字段值施加不区分大小写的唯一约束?
【发布时间】:2016-12-30 03:07:39
【问题描述】:

我想在表 AGENT 中添加一个名为 email 的字段。我希望 AGENT.email 的值在整个表中是唯一的,并且我希望这种唯一性不区分大小写。

例如,如果表中已存在“mary@usa.com”,则添加“MARY@USA.COM”将违反约束。我该怎么做?

【问题讨论】:

    标签: sql constraints firebird unique-constraint


    【解决方案1】:

    要施加不区分大小写的约束,最好的方法是使用不区分大小写的排序规则创建列,例如 unicode_ci_ai - 这种排序规则也是不区分重音的,您可能想要也可能不想要 - 并添加一个唯一约束 (或唯一索引)在该列上:

    create table addressbook
    (
        id integer not null,
        emailaddress varchar(150) character set utf8 collate unicode_ci_ai,
        constraint pk_addressbook primary key (id),
        constraint uc_emailaddress unique (emailaddress)
    );
    

    或将字段添加到现有表中:

    alter table addressbook
        add emailaddress2 varchar(150) character set utf8 
                constraint uc_emailaddress2 unique collate unicode_ci_ai
    

    替代排序规则将是unicode_ci(仅不区分大小写)或其他built-in case insensitive collations,具体取决于所使用的字符集,或create your own specific collation

    与 Gurwinder 提出的解决方案相比,此解决方案的优势在于它还允许您不敏感地选择大小写(和重音),而无需在 where 子句中使用 lower

    【讨论】:

      【解决方案2】:

      您可以像这样在表格上的电子邮件列的lower 上添加唯一索引:

      create unique index email_unq_idx on agent computed by (lower(email));
      

      【讨论】:

      • 我正在运行 Firebird 2.1
      • @Jonathan 干杯伙伴 :)
      • 您也可以对列使用不区分大小写的排序规则;稍后我会发布完整的答案。
      • 并且排序方式会更好 - 这将允许索引也可用于 SELECTs。表达式索引几乎只适用于唯一性检查
      猜你喜欢
      • 1970-01-01
      • 2013-05-30
      • 2020-12-25
      • 1970-01-01
      • 2011-04-26
      • 2020-07-22
      • 2017-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多