In MySQL sind NULL-Werte in Unique-Indizes mehrfach erlaubt – das lässt sich gezielt ausnutzen.
Einfachster Weg: NULL statt 0
Entfernen Sie die NOT NULL-Bedingung von Status und legen Sie einen Unique-Index auf (ContactId, PhoneId, Status) an. Verwenden Sie NULL für inaktive Datensätze – dann sind beliebig viele Inaktiv-Einträge erlaubt, aktive bleiben eindeutig.
Wenn NULL nicht geht: generierte Spalte (MySQL 5.7+)
CREATE TABLE IF NOT EXISTS `ContactPhone` (
`ContactPhoneId` int(10) unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
`ContactId` int(11) NOT NULL,
`PhoneId` smallint(5) unsigned NOT NULL,
`Status` tinyint(1) NOT NULL DEFAULT '1',
`StatusUnq` tinyint(1) AS (IF(Status <> 0, 1, NULL)) STORED NULL,
CONSTRAINT unique (ContactId, PhoneId, StatusUnq)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
insert into ContactPhone (ContactPhoneId, ContactId, PhoneId, Status) values (1, 1, 1, 1);
insert into ContactPhone (ContactPhoneId, ContactId, PhoneId, Status) values (2, 1, 1, 1); -- Duplicate key error
insert into ContactPhone (ContactPhoneId, ContactId, PhoneId, Status) values (3, 1, 1, 0);
insert into ContactPhone (ContactPhoneId, ContactId, PhoneId, Status) values (4, 1, 1, 0);
update ContactPhone set Status = 1 where ContactPhoneId = 4; -- Duplicate key error
Ohne generierte Spalte: Trigger
CREATE TRIGGER trbi_contactPhoneUnique BEFORE INSERT ON ContactPhone
FOR EACH ROW SET NEW.StatusUnq = IF(NEW.Status <> 0, 1, NULL);
CREATE TRIGGER trbu_contactPhoneUnique BEFORE UPDATE ON ContactPhone
FOR EACH ROW SET NEW.StatusUnq = IF(NEW.Status <> 0, 1, NULL);
Sollen unterschiedliche aktive Statuswerte erlaubt sein, lautet die Formel IF(NEW.Status <> 0, NEW.Status, NULL). Empfehlenswert ist InnoDB statt MyISAM, damit Unique-Indizes und Transaktionen zuverlässig funktionieren.