Question

I have a csv file that is formated as follows:

Rank, URL
1, www.google.com
2, www.facebook.com
etc...

I have a table with structure

url, source, date_added

Where each csv file has a different source ID.

I am using the following query to load my data

load data local infile 'this.csv' 
into table seeds.seed
fields terminated by ',';

Which doesn't quite do what I want but it's my starting point. What I want to do is select column 2 to be inserted as my URL field, and set the source to 0 for each entry. So I am thinking something like this...

load data local infile 'this.csv' 
into table seeds.seed(url, source)
select col1, '0'
fields terminated by ',';

What is the correct notation for col1? And am I missing any other key parts to the query?

Was it helpful?

Solution

LOAD DATA INFILE 'this.csv'
  INTO TABLE seed
  (col1) SET source = 0;
FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '"'
LINES TERMINATED BY '\r\n';

Have a look into SO answer.

This is the reference

OTHER TIPS

Query that ended up working

load data local infile 'this.csv' into table seeds.seed
fields terminated by ',' lines terminated by '\n'
(@col1,@col2) set url=@col2, source='0';

it's quite tricky using load data infile. I spent all last week trying to work it out with so many numerous errors. I'll give you my insights.

I can't see your create table statement so I don't know what datatypes you are using. If you have integer fields then you have to put at least a 0 in each field in your csv file even if it is wrong. you remove it later post import.

If your integer field is a auto_increment like a primary key then you can omit the field alltogether. don't make my mistake and just leave the field there with no values. Delete it completely otherwise your csv will start with a field terminator character and cause no end of issues.

load data infile 'file.csv'

into table mytablename

fields terminated by ','

lines terminated by '\r\n' - ( for windows)

ignore 1 lines (field1, field2, field4 etc.) - you list your fields in your csv there. If you have fields with no data then you can delete them from your csv and omit them from the list here too.

ignore 1 lines - ignores the first line of the csv which contains your field list.

set id=null,

field3=null;

I set my auto_increment id field to null as its not in the csv file and the mysql knows it exists and what to do with it.

Also set field3 to null because that had no values and was deleted from the csv file as an example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top