Mysql
 sql >> Database >  >> RDS >> Mysql

aggiungendo univoco alla chiave esterna esistente

Migliorerò questo mentre vado. MySQL onorerà i tuoi desideri e ti consentirà persino di spararti ai piedi mentre procedi:

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 dupe 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 devi portare con te con i tuoi upsert (leggi:lenti indici extra non necessari).

Quindi, se vuoi che sia il più snello possibile, come ho detto nei commenti, rilassa prima le cose rilasciando gli FK nelle tabelle figli, il riferimento primo. Vedi Questa risposta .

Quindi rilascia la chiave genitore non univoca corrente:

DROP INDEX index_name ON tbl_name;

Quindi aggiungi la chiave univoca nel genitore. Questo è il nuovo riferito :

CREATE UNIQUE INDEX idxName ON tbl_name (colName);

Quindi aggiungi gli FK nei bambini (il riferimento )

CREATE INDEX idxName ON child_tbl_name (colName);

Puoi ottenere i nomi delle chiavi show create table theTableName o da SHOW INDEX . Usa nomi nuovi per quelli nuovi, non importa.

Ad 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      |         |               |
+-------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+