views:

141

answers:

2

I am trying to export one field from a very large table - containing 5,000,000 records, for example - into a csv list - but not all together, rather, 100,000 records into each .csv file created - without duplication. How can I do this, please?

I tried

SELECT field_name
  FROM table_name
 WHERE certain_conditions_are_met
  INTO OUTFILE /tmp/name_of_export_file_for_first_100000_records.csv
        LINES TERMINATED BY '\n'
 LIMIT 0 , 100000

that gives the first 100000 records, but nothing I do has the other 4,900,000 records exported into 49 other files - and how do I specify the other 49 filenames?

for example, I tried the following, but the SQL syntax is wrong:

SELECT field_name
  FROM table_name
 WHERE certain_conditions_are_met
  INTO OUTFILE /home/user/Eddie/name_of_export_file_for_first_100000_records.csv
        LINES TERMINATED BY '\n'
 LIMIT 0 , 100000
  INTO OUTFILE /home/user/Eddie/name_of_export_file_for_second_100000_records.csv
        LINES TERMINATED BY '\n'
 LIMIT 100001 , 200000

and that did not create the second file...

what am I doing wrong, please, and is there a better way to do this? Should the LIMIT 0 , 100000 be put Before the first INTO OUTFILE statement, and then repeat the entire command from SELECT for the second 100,000 records, etc?

Thanks for any help.

Eddie

+1  A: 

If you're running on a UNIX-like OS, why not just select the whole lot and pipe the output through:

split --lines=100000

As proof of concept:

echo '1
2
3
4
5
6
7
8
9' | split --lines=3

creates three files xaa, xab and xac containing the lines 1,2,3, 4,5,6 and 7,8,9 respectively.

Or, even on other operating systems, you can get the GNU tools, like GnuWin32, where split is in coreutils.

paxdiablo
A: 

You can use loop and sub-query to generate the files. following procedure can give you clue how to do that(it may have syntax error):

CREATE PROCEDURE exportSplitter(partsCount)
BEGIN
  SET rowCount = select count(*) from table;
  SET pageRowCount = rowCount / partsCount;
  SET p1 = 0;
  label1: LOOP
    SET p1 = p1 + 1;
    SELECT field_name
      FROM (SELECT * from table_name WHERE certain_conditions_are_met order by id LIMIT p1*pageRowCount) order by id desc LIMIT pageRowCount
        INTO OUTFILE /home/user/Eddie/p1
            LINES TERMINATED BY '\n'
    IF p1 < partCount THEN ITERATE label1; END IF;
    LEAVE label1;
  END LOOP label1;
END
Ehsan