Exporting a MySQL table into a CSV file

前端 未结 4 1163
孤独总比滥情好
孤独总比滥情好 2020-12-14 01:45

I have a MySQL table which has to be taken out as a CSV file. The query I used is

SELECT \"ID\",\"NAME\",\"SALARY\",\"SAL1\",\"SAL2\",\"SAL3\",\"SAL4\",\"SAL         


        
4条回答
  •  萌比男神i
    2020-12-14 02:02

    DESCRIBE addstock25;
    

    Strip the first column and the first three entries of that column (it depends on your usage). You will get the list of fields in addstock25.

    This will bring only field names using virtual tables derived in core... called information schema.

    SELECT `COLUMN_NAME` 
    FROM `INFORMATION_SCHEMA`.`COLUMNS` 
    WHERE `TABLE_NAME`='foo';
    

    Let’s say the name of this query would be sq_fieldnamelist.

    So, the above table has one column and it has the field names of the "foo" table.

    If directly writing like

    SELECT (sq_fieldnamelist)
    UNION ALL
    SELECT *
    FROM addstock25
    INTO OUTFILE "E:\\JOSE DATA\\addstock7.csv"
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n
    

    MySQL will give an error. "subquery returns multiple rows"

    We must edit sq_fieldnamelist to concatenate all entries back to back, separated with commas.

    Select GROUP_CONCAT(COLUMN_NAME)
    FROM
    (SELECT `COLUMN_NAME` 
    FROM `INFORMATION_SCHEMA`.`COLUMNS` 
    WHERE `TABLE_NAME`='ffd_companies'
    LIMIT 3,100
    ) AS fafa
    GROUP BY 'COLUMN_NAME' // This group by is just to make group concatenation work
    

    Let's say this is sq_fieldnamelist2.

    If we edit sq_fieldnamelist like this, it will return only one value which is all field names separated with commas. So now we can put this subquery in your select statement to acquire the needed fields.

    SELECT (sq_fieldnamelist2)
    UNION ALL
    SELECT *
    FROM addstock25
    INTO OUTFILE "E:\\JOSE DATA\\addstock7.csv"
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n
    

    You need to edit LIMIT 3,100 in sq_fieldnamelist2 for you own purpose.

    Let's say your table is like fil1, fil2...filN, sal1, sal2, sal3...., salI. To see the only salary fields, you should use LIMIT N, x > I+N. If you want to see all, use LIMIT 0, x > N+I.

提交回复
热议问题