简体   繁体   中英

How do I import a CSV with numerous date columns into a table using SQL statements in MySQL?

Say I have a CSV which looks a bit like this:


Year 2013, 2012, 2011, 2010, 2009, etc.

Blue, 47, 11, 23, 45, etc.

Red, 32, 73, 52, 88, etc.

Green, 68, 92, 433, 42, etc.

where the number of years is too tedious to enter in by hand as separate columns.


And I'd like to load all this info into a table

Blob{Color, year, amount}

How would I go about doing this programatically in MySQL (or any other SQL)? I get that you can import CSV data into a table with a LOAD DATA INFILE, but my table doesn't have anything like the structure of the CSV. Do I really have to first write a CREATE TABLE listing every single year number in the data set as attributes before iterating over all the elements to put it in 'Blob'? Surely there's a more programatic way of doing things.

In psuedo code using three simple arrays, assuming RGB rows are always in that order

open the file
load the first line
chop off 'Year,'
split by ',' in to an array of years
create a 2d array, where one on the values is colour the other is column position
load the next line, chop off the color, split by ',' and stores as say Colours[Red]
do the same for the green and blue rows
close the file

then say something like

for index = 0 to years.length - 1 do
  for colour = red to blue
    sql = 'Insert Table Blob(year,colour,amount) values(years[index], colour, colours[colour][index])'
    execute the sql
  end for
end for

You could make this more efficient probably, whether it's worth would be dependent on volume and frequency.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM