如何对 Firebird 字段值施加不区分大小写的唯一约束?
How do you impose a case insensitive unique constraint on a Firebird field value?
我想向 table 代理添加一个名为电子邮件的字段。我希望 AGENT.email 的值在 table 中是唯一的,并且我希望这种唯一性不区分大小写。
例如,如果 table 中已经存在 "mary@usa.com",则添加 "MARY@USA.COM" 将违反约束。我该怎么做?
您可以在 table 的电子邮件列的 lower
上添加唯一索引,如下所示:
create unique index email_unq_idx on agent computed by (lower(email));
要施加不区分大小写的约束,最好的方法是使用不区分大小写的排序规则创建列,例如 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)
);
或将字段添加到现有 table:
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 depending on the character set used, or to create your own specific collation.
与 Gurwinder 提出的解决方案相比,此解决方案的优势在于它还允许您不区分 select 大小写(和重音),而不必在 where 子句中使用 lower
。
我想向 table 代理添加一个名为电子邮件的字段。我希望 AGENT.email 的值在 table 中是唯一的,并且我希望这种唯一性不区分大小写。
例如,如果 table 中已经存在 "mary@usa.com",则添加 "MARY@USA.COM" 将违反约束。我该怎么做?
您可以在 table 的电子邮件列的 lower
上添加唯一索引,如下所示:
create unique index email_unq_idx on agent computed by (lower(email));
要施加不区分大小写的约束,最好的方法是使用不区分大小写的排序规则创建列,例如 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)
);
或将字段添加到现有 table:
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 depending on the character set used, or to create your own specific collation.
与 Gurwinder 提出的解决方案相比,此解决方案的优势在于它还允许您不区分 select 大小写(和重音),而不必在 where 子句中使用 lower
。