Affinirò questo man mano. MySQL ti lascerà allegramente spararti su un piede:
create table t9 ( id int auto_increment primary key, thing varchar(20) not null, key(thing), unique key (thing), unique key `yet_another` (thing) ); -- warning 1831: duplicate index show create table t9; CREATE TABLE `t9` ( `id` int(11) NOT NULL AUTO_INCREMENT, `thing` varchar(20) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `thing_2` (`thing`), UNIQUE KEY `yet_another` (`thing`), KEY `thing` (`thing`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; Quindi guarda tutto il bagaglio che poi ti porti dietro in ogni upsert — indici lenti, ridondanti, inutili.
Se lo vuoi il più snello possibile, sbroglia prima le cose eliminando le chiavi esterne nelle tabelle figlie, dal lato che referenzia per primo. Vedi questa risposta per la sintassi.
Poi elimina l'attuale chiave padre non univoca:
DROP INDEX index_name ON tbl_name; Aggiungi la chiave univoca sul padre — questa diventa il nuovo indice referenziato:
CREATE UNIQUE INDEX idxName ON tbl_name (colName); Poi ricrea le chiavi esterne sui figli, il lato che referenzia:
CREATE INDEX idxName ON child_tbl_name (colName); Ottieni i nomi delle chiavi esistenti da show create table theTableName o da SHOW INDEX. Nomi nuovi per quelle nuove vanno bene; i nomi non contano.
Per esempio:
mysql> show index from t9; +-------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | +-------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+ | t9 | 0 | PRIMARY | 1 | id | A | 0 | NULL | NULL | | BTREE | | | | t9 | 0 | thing_2 | 1 | thing | A | 0 | NULL | NULL | | BTREE | | | | t9 | 0 | yet_another | 1 | thing | A | 0 | NULL | NULL | | BTREE | | | | t9 | 1 | thing | 1 | thing | A | 0 | NULL | NULL | | BTREE | | | +-------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+ Il motivo per cui elimini prima le chiavi esterne figlie è l'ordine: MySQL non ti permette di eliminare un indice da cui dipende un vincolo di chiave esterna, quindi i vincoli devono sparire prima dell'indice e tornare dopo.