First steps in moving a CSV to a MySQL relational database. CSV structure != MySQL structure -


i have csv in following format:

module, topic, sub-topic 

it needs able imported mysql database has following format:

create table `modules` (   `id` varchar(4) not null,   `name` varchar(20) not null,   `active` tinyint(1) not null default '1',   primary key (`id`),   unique key `name` (`name`) ) engine=innodb default charset=latin1;  create table `topics` (   `id` int(3) not null auto_increment,   `name` varchar(30) not null,   `module` varchar(30) not null,   `active` tinyint(1) not null default '1',   primary key (`id`),   unique key `id` (`id`),   key `module_ref_idx` (`module`),   constraint `module` foreign key (`module`) references `modules` (`id`) on delete no action on update no action ) engine=innodb auto_increment=648 default charset=latin1;  create table `subtopics` (   `id` int(3) not null auto_increment,   `name` varchar(30) not null,   `topic` int(3) not null,   `active` tinyint(1) not null default '1',   primary key (`id`),   unique key `id` (`id`),   key `topic_idx` (`topic`),   constraint `topic` foreign key (`topic`) references `topics` (`id`) on delete no action on update no action ) engine=innodb auto_increment=41 default charset=latin1; 

i know i'm able insert data csv file mysql , keep data integrity, i'm not sure how. data csv needs put in 'name' fields in each table, while keeping relationship of data in tact.

i'm playing in workbench right , can't right.

thanks in advance.

create table load csv (a temporary 1 can used too)

create table `tmp_subtopics` (     `module` varchar(50) null,     `topic` varchar(50) null,     `subtopic` varchar(50) null ) 

load csv (you might need additional options encoding, field names.. etc)

 load data infile 'file.csv' table tmp_subtopics 

insert modules

 insert ignore modules (name)  select distinct module tmp_subtopics 

insert topics

insert ignore topics (name,module) select distinct     tmp.topic,     m.id tmp_subtopics tmp join modules m on m.name = tmp.module 

insert subtopics

insert subtopics (name,topic) select     tmp.subtopic,     t.id tmp_subtopics tmp join topics t on t.name = tmp.topic 

also:

unique key id (id) redundant, should remove it.

the module field in topics table should int not varchar.


Comments