具有一个可空键和一个外键的唯一索引

Unique index with one nullable key and foreign key

我们有以下 table,我们 运行 遇到了一个问题,即我们的唯一密钥不起作用 (as expected)。

CREATE TABLE `documentation_photos` (
  `commissionID` smallint(5) unsigned NOT NULL,
  `periodID` smallint(5) unsigned NOT NULL,
  `carreirID` int(11) NOT NULL,
  `groupID` smallint(5) unsigned DEFAULT NULL,
  `order` tinyint(4) NOT NULL,
  `file` varchar(200) NOT NULL,
  UNIQUE KEY `idZak_UNIQUE` (`commissionID`,`periodID`,`carreirID`,`groupID`,`order`),
  KEY `ncis & obdobi & idZak` (`commissionID`,`periodID,`carreirID``),
  KEY `fotodoc_skupina` (`idSkup`),
  CONSTRAINT `fotodoc_` FOREIGN KEY (`groupID`) REFERENCES `groups` (`groupID`),
  CONSTRAINT `fotodoc_zaknos` FOREIGN KEY (`commissionID`, `periodID`, `carreirID`) REFERENCES `carrier_of_commission` (`commissionID`, `periodID`, `carreirID`) ON DELETE CASCADE
);

我看到了这个问题,它描述了 NULL 每次出现都被认为是唯一的,但它给我们带来了很多问题。我找到的唯一一个是用于 Postgres 的...

|--------------|----------|-----------|---------|-------|---------|
| commissionID | periodID | carrierID | groupID | order | file    |
|--------------|----------|-----------|---------|-------|---------|
| 1140         | 117      | 2235      | null    | 1     | photo-1 |
|--------------|----------|-----------|---------|-------|---------|
| 1140         | 117      | 2235      | null    | 1     | photo-1 | -- This is duplicate
|--------------|----------|-----------|---------|-------|---------|
| 1140         | 117      | 2235      | null    | 2     | photo-2 |
|--------------|----------|-----------|---------|-------|---------|
| 1140         | 117      | 2235      | null    | 1     | photo-1 | -- This is duplicate
|--------------|----------|-----------|---------|-------|---------|

我想将 null 视为单个值。

我们希望使用 unique/primary 键并尽可能保留外键。 在 MySQL 中是否有一些已知的解决方案?

每个 NULL 都是唯一的(两个 NULL 不相等)- 不检查索引表达式中包含 NULL 的行的唯一性,不检查 FK 表达式中包含 NULL 的行的引用完整性。

Is there some known solution for this in MySQL?

使用生成的列将 NULL 替换为一些确定但逻辑上不可能的文字值,在 index/FK 表达式中使用此列而不是 nullale 列。