在可空字段上定义的 MySql 唯一约束到底是如何工作的?

How exactly works the MySql unique constraint defined on a nullable field?

我不太喜欢数据库(我正在使用 MySql),我对设置的 **unique 约束有以下疑问 可为空的字段

据我所知,UNIQUE 约束确保列中的所有值都不同。

但是如果我在 table.

的可空字段上设置唯一约束会发生什么

例如我有这个 DDL table 定义:

CREATE TABLE results (
  id        BigInt UNSIGNED NOT NULL AUTO_INCREMENT,
  sample_id VarChar(128) NOT NULL,
  doi       VarChar(128),
  result    VarChar(2) NOT NULL,
  error     Text, 
  PRIMARY KEY (
      id
  )
) ;
ALTER TABLE results COMMENT = '';
ALTER TABLE results ADD CONSTRAINT fk_results_pgrfas FOREIGN KEY (sample_id)
  REFERENCES pgrfas (sample_id)
  ON DELETE NO ACTION 
  ON UPDATE NO ACTION;
ALTER TABLE results ADD CONSTRAINT u_results UNIQUE 
    (doi);

其中 doi 字段可为空。在此字段上设置了唯一约束,因为我想防止此 table 的更多行具有与 doi 字段相同的值。

每一行需要有不同的 doi 值,但这个字段可以为空,所以我需要让多行有 doi 字段设置为空。

唯一约束仅适用于设置值,或者也防止不同的行具有此 doi 字段的 null 值? (这对我来说是个问题,因为我需要唯一约束仅适用于非空值)。

那么我可以插入多个 doi 字段设置为空的行吗?

答案深藏在 documentation 中 for create index:

A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL.

请注意,此行为因数据库而异。有些只允许一个 NULL 值。

为了您的目的,unique index/constraint 可以满足您的需要。