# DIBE - Database Normalisatie ## MyISAM -> InnoDB De meeste tabellen gebruiken nu nog MyISAM, die moeten gemigreerd worden naar InnoDB. ## Voorbeeld tabel 'charter_type' De tabel 'charter_type' beschrijft de relatie tussen een 'charter' en een property 'type'. Die property is eigen aan een charter (type is te generiek). De propertytabel krijgt dus de naam 'charter_type', de relatietabel hernoemen we naar charter__charter_type Methode - Hernoem charter_type naar charter__charter_type - Maak een nieuwe tabel 'charter_type' aan met velden 'charter_type_id', 'name_nl', 'name_en', 'name_fr' - Voeg foreign key veld 'charter_type_id' toe aan charter__charter_type. Bij het aanmaken mag het veld nog null zijn en mag er nog geen key restrictie zijn. - Dump alle unieke waarden voor de charter_type property in de nieuwe tabel Dit kan bijna automatisch via deze sql code: ``` RENAME TABLE db_dibe.charter_type TO db_dibe.charter__charter_type; ALTER TABLE db_dibe.charter__charter_type ADD charter_type_id BIGINT(20) UNSIGNED NULL; CREATE UNIQUE INDEX charter__charter_type_charter_type_id_IDX USING BTREE ON db_dibe.charter__charter_type (charter_type_id); CREATE TABLE `charter_type` ( `charter_type_id` bigint(20) unsigned NULL AUTO_INCREMENT, `name_nl` varchar(100) NOT NULL, `name_en` varchar(100) NOT NULL, `name_fr` varchar(100) NOT NULL, PRIMARY KEY (`charter_type_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; INSERT INTO charter_type (name_nl, name_en, name_fr) SELECT DISTINCT t.type_nl, t.type_en, t.type_fr FROM charter__charter_type as t; UPDATE charter__charter_type as ct, charter_type as t set ct.charter_type_id = t.charter_type_id where ct.type_nl = t.name_nl and ct.type_en = t.name_en and ct.type_fr = t.name_fr; ALTER TABLE charter__charter_type MODIFY COLUMN charter_type_id bigint(20) unsigned NOT NULL; ``` Als alles goed is gegaan kan je de oorspronkelijke velden wissen en foreign key restricties toevoegen. Uiteindelijk bekom je dan een schema zoals hieronder: ``` CREATE TABLE `charter__charter_type` ( `dummy_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `charter_id` bigint(20) unsigned NOT NULL, `charter_type_id` bigint(20) unsigned NOT NULL, PRIMARY KEY (`dummy_id`), KEY `charter__charter_type_charter_type_id_IDX` (`charter_type_id`) USING BTREE, KEY `charter__charter_type_charter_id_IDX` (`charter_id`) USING BTREE, CONSTRAINT `charter__charter_type_FK` FOREIGN KEY (`charter_id`) REFERENCES `charter` (`charter_id`), CONSTRAINT `charter__charter_type_FK_1` FOREIGN KEY (`charter_type_id`) REFERENCES `charter_type` (`charter_type_id`) ) ENGINE=InnoDB AUTO_INCREMENT=42812 DEFAULT CHARSET=utf8; ```