【发布时间】:2016-12-30 03:07:39
【问题描述】:
我想在表 AGENT 中添加一个名为 email 的字段。我希望 AGENT.email 的值在整个表中是唯一的,并且我希望这种唯一性不区分大小写。
例如,如果表中已存在“mary@usa.com”,则添加“MARY@USA.COM”将违反约束。我该怎么做?
【问题讨论】:
标签: sql constraints firebird unique-constraint
我想在表 AGENT 中添加一个名为 email 的字段。我希望 AGENT.email 的值在整个表中是唯一的,并且我希望这种唯一性不区分大小写。
例如,如果表中已存在“mary@usa.com”,则添加“MARY@USA.COM”将违反约束。我该怎么做?
【问题讨论】:
标签: sql constraints firebird unique-constraint
要施加不区分大小写的约束,最好的方法是使用不区分大小写的排序规则创建列,例如 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。
【讨论】:
您可以像这样在表格上的电子邮件列的lower 上添加唯一索引:
create unique index email_unq_idx on agent computed by (lower(email));
【讨论】: