简体   繁体   中英

exporting data to CSV file using SELECT mysql query

Usually, to export CSV reports from a mysql server, I connect & run a query on the server, save the results into a text file, and import the file to excel by specifying to separate the columns using the pipe delimited character.

I need to run a report on a table with a MEDIUMTEEXT column type, which contains comma characters, and line breaks (\\n).

The line breaks and commas symbols are breaking the table layout.

SELECT `number`,REPLACE(`description`, ',', ''),  mr.`dateInserted` FROM 
`mr`  WHERE mr.dateInserted >= '2012-01-01' AND mr.dateInserted <= '2012-01-31'

I solved the comma issues by using the MySQL REPLACE function, however, how can I remove the line breaks from the results?

You can do this with an query, here's an example.

SELECT
  id,
  name,
  email
INTO
  OUTFILE '/tmp/result.csv'
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY ‘\\’
LINES TERMINATED BY '\n'
FROM users WHERE 1

You can also use a combination of a "view" and "mysqldump".

http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html

Char(13) is a carriage return

Char(10) is a line feed

Try nested replace functions for path of least resistance :)

SELECT 
    `number`, 
    REPLACE(REPLACE(REPLACE(`description`, ',', ''), CHAR(13),''), CHAR(10),''),
    mr.`dateInserted`
FROM
    `mr`
WHERE
    mr.dateInserted >= '2012-01-01' 
AND 
    mr.dateInserted <= '2012-01-31'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM