Tuesday, May 11, 2010

MYSQL Export

I involve in some project where I need to do Export mysql table into .csv file

First of all, the table structure
CREATE TABLE IF NOT EXISTS `contacts` (
`id` int(20) unsigned NOT NULL auto_increment,
`name` varchar(200) NOT NULL,
`phonenumber` varchar(50) NOT NULL,
`group` varchar(50) NOT NULL,
`created` datetime default NULL,
`modified` datetime default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Contact detail' AUTO_INCREMENT=5 ;

INSERT INTO `contacts` (`id`, `name`, `phonenumber`, `group`, `created`, `modified`) VALUES
(1, 'Mr Number 1', '0126784669', 'Customer', '2010-05-12 09:50:57', '2010-05-12 09:50:57'),
(2, 'Mrs Testing', '0136785186', 'Customer', '2010-05-12 09:50:57', '2010-05-12 09:50:57'),
(3, 'Mr Bone', '0184531256', 'Staff', '2010-05-12 09:52:41', '2010-05-12 09:52:41'),
(4, 'Mr Gray', '0104578996', 'Staff', '2010-05-12 09:52:41', '2010-05-12 09:52:41');


Here is how to export the file into .csv
This code is in many blog and other tutorial
SELECT *
INTO OUTFILE "C:/Documents and Settings/asipo/My Documents/Downloads/contacts.csv"
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM contacts
WHERE `group` = 'Customer';


But most of the website I found, does not show how to create a .csv file with a extra column header description into it.
So this is how I do it
SELECT 'Id', 'Name', 'Phone Number', 'Group', 'Created', 'Modified'
FROM `contacts` LIMIT 1
UNION
SELECT *
INTO OUTFILE "C:/Documents and Settings/asipo/My Documents/Downloads/contacts.csv"
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY ''
LINES TERMINATED BY '\n'
FROM `contacts`

As a result, you going to see somthing like this


Thats all

No comments: