1

Imagine you have a CSV file with only text in it and line ending \r\n. like this:

abc
def
hij
...
xyz

You want to import this file in an existing multi-column table, where each line of text needs to go in a line of one specific (currently empty) column (lets name it needed) of the table. Like this:

| a | b | c |needed|
|foo|bar|baz|______|<-- abc
|foo|bar|baz|______|<-- def
...
|foo|bar|baz|______|<-- xyz

The data from the CSV file does not need to be inserted in a certain order. It really does not matter which field of needed has which data from the CSV in it, as long as every line gets imported, everything is fine.

I've tried lots of things and its driving me mad, but I can't figure out, how this could be done. Can this be solved somehow with LOAD DATA INFILE and update/replace/insert command? What would you do in a case like this? Is it even possible with mysql? Or do I need a custom php script for this?

I hope the question is clear enough. Please ask, if something is unclear to you.

4

2 回答 2

2

OK, here you go...

Add a new column to stuff populated with 1-600,000

ALTER TABLE stuff ADD COLUMN newId INTEGER UNIQUE AUTO_INCREMENT;

Create a temp table for your CSV file

CREATE TABLE temp (
    id INTEGER PRIMARY KEY AUTO_INCREMENT,
    data VARCHAR(32)
);

I'm guessing the required length of the data.

Import into the temporary table

LOAD DATA INFILE <wherever> INTO TABLE temp;

Add the data to stuff

UPDATE stuff AS s
JOIN temp AS t ON t.id=s.newId
SET s.needed=t.data;

Tidy up

DROP TABLE temp;
ALTER TABLE stuff DROP COLUMN newId;

I must admit that I haven't tested the LOAD DATA INFILE or the UPDATE statements, but I have checked all the table fiddling. In particular, MySQL will populate the newId column with consecutive numbers.

I don't think there will be a problem if the number of rows in stuff doesn't match the number of lines in your csv file - obviously, there will be a few rows with needed still NULL if there are fewer lines than rows.

于 2013-06-15T20:37:21.250 回答
0

Most easiest way I found was with Libreoffice Calc+Base. Import/Export Data in Base.

But becarefull,if you have "not null" options in columns and by mistake there is a cell which has no data in it, that row will be skiped.

So first disable the not null options from columns.

Oh and there is Microsoft Office Excel way,but I did not done it since it required a plugin to install and I was lazy.

于 2013-06-15T19:50:30.867 回答