Import Excel Data to Relational Tables at MySQL

后端 未结 3 720
自闭症患者
自闭症患者 2021-01-06 10:37

I have three tables at my MySQL database. First one is cities, second one is towns and third one is districts. Every town has many districts. My table details:

3条回答
  •  猫巷女王i
    2021-01-06 10:55

    You could save your Excel sheet as in a CSV file, then import such file in a temporary MySQL table with the same columns of the Excel sheet by using the LOAD DATA INFILE command, and finally split the temporary table records in the three tables "cities", "towns" and "districts".
    A premise: since none of the "id" fields is present in the Excel file, I suppose that all the ids are "auto_increment" fields; also, the "continent" field of the "towns" table will always be set to a blank value, since this field is not present in your Excel sheet; finally, I'll assume that all the "name" fields have a maximum length of 255 characters.
    Starting from your sample data, by exporting the Excel Sheet in the CSV format and saving (for example) into the "C:\Temp\excel.csv" file, you should get something like this:

    "city name","town name","district name"
    "X","Y","A"
    "X","Y","B"
    "X","K","C"
    "X","K","D"
    

    To import this file into your MySQL database, create a "excel2mysql.sql" file with the following content, and execute it:

    DROP TABLE IF EXISTS excel_table;
    CREATE temporary TABLE excel_table (
      city_name VARCHAR(255),
      town_name VARCHAR(255),
      district_name VARCHAR(255)
    ) DEFAULT CHARSET utf8;
    
    LOAD DATA LOCAL INFILE 'C:/Temp/excel.csv' 
    INTO TABLE excel_table 
    CHARACTER SET utf8
    FIELDS TERMINATED BY ',' 
    ENCLOSED BY '"' 
    LINES TERMINATED BY '\n' 
    IGNORE 1 LINES;
    
    DROP TABLE IF EXISTS cities;
    CREATE TABLE cities (
      city_id int NOT NULL auto_increment,
      city_name VARCHAR(255),
      primary key (city_id)
    ) DEFAULT CHARSET utf8;
    
    INSERT INTO cities 
      SELECT distinctrow NULL, city_name 
        FROM excel_table 
       ORDER BY city_name;
    
    DROP TABLE IF EXISTS towns;
    CREATE TABLE towns (
      town_id int NOT NULL auto_increment,
      city_id int NOT NULL,
      town_name VARCHAR(255),
      continent VARCHAR(255),
      primary key (town_id)
    ) DEFAULT CHARSET utf8;
    
    INSERT INTO towns 
      SELECT distinctrow NULL, city_id, town_name, '' 
        FROM excel_table, cities 
       WHERE cities.city_name=excel_table.city_name 
       ORDER BY town_name;
    
    DROP TABLE IF EXISTS districts;
    CREATE TABLE districts (
      district_id int NOT NULL auto_increment,
      town_id int NOT NULL,
      district_name VARCHAR(255),
      primary key (district_id)
    )  DEFAULT CHARSET utf8;
    
    INSERT INTO districts 
      SELECT distinctrow NULL, town_id, district_name 
        FROM excel_table, towns 
       WHERE towns.town_name=excel_table.town_name 
       ORDER BY district_name;
    

提交回复
热议问题