java - 可以修改sql中的唯一约束吗?

标签 java mysql sql sqlite

我使用唯一约束来避免重复(空值除外),因为此列可以保持为空(它不是必填字段,但它有助于搜索,例如通过电子邮件等搜索)

在上述情况下,选择唯一约束是否正确?

替代方案 由于 unique 只允许有一个空值,因此是否可以为 unique 约束生成不同的默认值?即每行都是唯一的。

最佳答案

您将问题标记为 ,所以我将介绍两者。

SQLite

在 SQLite 中,UNIQUE 约束将按照您的意愿工作。

UNIQUE constraint 的文档说:

For the purposes of UNIQUE constraints, NULL values are considered distinct from all other values, including other NULLs.

CREATE INDEX 的文档说:

If the UNIQUE keyword appears between CREATE and INDEX then duplicate index entries are not allowed. Any attempt to insert a duplicate entry will result in an error. For the purposes of unique indices, all NULL values are considered different from all other NULL values and are thus unique. This is one of the two possible interpretations of the SQL-92 standard (the language in the standard is ambiguous) and is the interpretation followed by PostgreSQL, MySQL, Firebird, and Oracle. Informix and Microsoft SQL Server follow the other interpretation of the standard.

但是,在大多数其他数据库中,UNIQUE 约束的列不能为 NULL,因此我建议改用 UNIQUE INDEX,以保持一致性,以免混淆。

MySQL

在 MySQL 中,UNIQUE 约束将按照您的意愿工作。

Unique Indexes 的文档说:

A UNIQUE index permits multiple NULL values for columns that can contain NULL.

UNIQUE KEY 是 UNIQUE INDEX 的同义词。

SQL 服务器

正如 SQLite 文档中提到的,Microsoft SQL Server 对 UNIQUE 索引的 NULL 处理遵循不同的解释。

UNIQUE INDEX 的文档说:

Columns that are used in a unique index should be set to NOT NULL, because multiple null values are considered duplicates when a unique index is created.

要解决这个问题,请使用过滤索引,例如

CREATE UNIQUE INDEX Person_Email
    ON Person ( Email )
    WHERE Email IS NOT NULL;

关于java - 可以修改sql中的唯一约束吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61156323/

相关文章:

java - 从 Java JNI DLL 写入 stdout - 输出仅在应用程序退出时出现

java - 如何在 setoncompletionlistener 之后使用相同的按钮?

mysql - rails : mysql load error when starting rails server

sql - 将小数点添加到表中的数据

sql - EXECUTE 后的事务计数表明 BEGIN 和 COMMIT 语句的数量不匹配。先前计数 = 1,当前计数 = 0

SQL 组合两个 SQL 语句的输出以返回一个 bool 值

java - 填充对象数组

MySQL 无法显示列名 "Group"

mysql - 如何对 NULL 字段进行分组

java - 如何在编程语言中生成一些长度固定为 r 的同分布伪随机 vector ?