mysql outfile column with leading zeros

912 Views Asked by At

I am trying to export data into a csv file but my leading zeros are getting chopped... I CANNOT modify the data after it is pulled so LPAD is not an option. Also, ID is not a set length... it could be 6 chars long, or up to 11. It may have letters as well (in which case the csv displays those values as strings. Anyway, the fields with leading zeros have the leading zeros in the database and are stored as varchar. I need to pull those values and display them in the csv with the zeros:

SELECT
    'ID',
    'Par 1',
    'Par 2'
UNION
(SELECT
    result.id as 'ID',      
    COALESCE(sum(if(result.parameter = '10001', result.result, NULL)),'-') as 'Par 1',
    COALESCE(sum(if(result.parameter = '10002', result.result, NULL)),'-') as 'Par 2'
    INTO OUTFILE '/tmp/file.csv' FIELDS TERMINATED BY ','  ENCLOSED BY '\"' 
FROM (
    SELECT
        event.id,
        resultset.parameter_cd,
        resultset.result
    FROM event
    Inner Join resultset ON resultset.id = event.id
    ) as result
group by result.id
order by
    result.id ASC )

in this case 'id' may have leading zeros... The result set from mysql shows them, however in the exported csv they are completely stripped out????

1

There are 1 best solutions below

1
On

As a workaround surround the id with double quotes and take the enclosed by out as the numeric fields don't need them

(SELECT
    concat ('\"', result.id, '\"') as 'ID',
    COALESCE(sum(if(result.parameter = '10001', result.result, NULL)),'-') as 'Par 1',
    COALESCE(sum(if(result.parameter = '10002', result.result, NULL)),'-') as 'Par 2'
    INTO OUTFILE '/tmp/file.csv' FIELDS TERMINATED BY ','