My question is not how to export .csv file data into MySQL. My question is how to first add a column to the existing table and then populate that newly created column with the data from .csv file. For example, imagine I have a table with 2 columns right now and 400 rows:
+----------------+------------+
| username | first_name |
+----------------+------------+
| abc | Hun |
+----------------+------------+
...
I have this .csv file (also with 400 rows):
## column1 ##
ID,75u
PID,2_3_b
LID,3_b
...
This is what I have tried to do:
LOAD DATA INFILE '/path/to/file/example.csv'
INTO TABLE my_table
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(@col1, @col2) SET new_column = @col2;
I received this error afterwards:
ERROR 1054 (42S22): Unknown column 'new_column' in 'field list'
So I had to create a new column with this name:
ALTER TABLE my_table ADD new_column VARCHAR(400) AFTER first_name;
After this, I was able to insert the data from .csv file but what it did was this:
- The data were appended vertically (instead of horizontally). i.e., my table now has 800 rows because it inserted new .csv data below old data while giving
null
values (for 401-800 rows) to 2 pre-existing columns.
How can I append the new column to the table and then append .csv data to that new column horizontally (ideally in 1 step)?