gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:44:42 27 4
gpt4 key购买 nike

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

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

替代方案由于 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com