2014-09-03 210 views
0

我有一個導出爲CSV文件的MySQL查詢。收到CSV的人要求我添加列標題。很顯然,我可以在查詢中硬編碼它們,但是想知道是否有辦法返回一個包含所有已查詢列的名稱的行?mysql查詢返回列名

我目前的查詢如下 - 我希望以編程方式包含列標題,如果我可以只是萬一我忘記更改它時進行更改。

感謝

SET @sql_text = 
    CONCAT (
    "SELECT 
     cf_id as FoundUsFrom, 
     firstname as CustomerName1, 
     lastname as CustomerName2, 
     address1 as CAddress1, 
     address2 as CAddress2, 
     '' as CAddress3, 
     towncity as CCity, 
     postcode as CPostCode, 
     email as 'email', 
     telephone as HomePhone, 
     mobile as MobilePhone, 
     '' as WorkPhone, 
     chidname as PName, 
     '' as ToBeAged, 
     partyaddress1 as PAddress1, 
     partyaddress2 as PAddress2, 
     '' as PAddress3, 
     partytowncity as PCity, 
     partypostcode as PPostCode, 
     /*NEED VALIDATION*/ 
     celebrating as PType, 
     partydate as PDate, 
     partyboffinstart as PTime, 
     specialinstructions as SpecialInst, 
     numberguests as Guests, 
     IF(airexp = '','N','Y') as Air, 
     IF(chemcocklngexp = '','N','Y') as CocktailLong, 
     IF(chemcockshtexp = '','N','Y') as CocktailShort, 
     IF(chemreact = '','N','Y') as Reactions, 
     IF(dryicebolton = '','N','Y') as DryIce, 
     IF(electricitybolton = '','N','Y') as Electricity, 
     IF(flightbolton = '','N','Y') as Flight, 
     IF(fourelementsbolton = '','N','Y') as Elements, 
     IF(magicbolton = '','N','Y') as Magic, 
     IF(slimebolton = '','N','Y') as Slime, 
     IF(sweetbolton = '','N','Y') as Sweets, 
     IF(miniimpsbolton = '','N','Y') as MiniImps, 
     IF(extravaganzabolton = '','N','Y') as Extravaganza, 
     IF(dryicecreambolton = '','N','Y') as AIceCream, 
     IF(rocketbolton = '','N','Y') as ARocket, 
     IF(foodbreakbolton = '','N','Y') as AFood, 
     partybags as PBags, 
     deluxepartybags as PDBags 

INTO OUTFILE 'PATHTO/data/bookings", 
DATE_FORMAT(NOW(), '%Y%m%d%s'), 
".csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' 
LINES TERMINATED BY '\n' 
FROM sb_chronoforms_data_bookingformcombined" 
); 

PREPARE s1 FROM @sql_text; 
EXECUTE s1; 
DROP PREPARE s1; 
+0

您可以使用union;)在第一行返回列名稱 – 2014-09-03 16:54:54

+0

這可能有助於[如何將表列標題添加到sql select語句](http://stackoverflow.com/questions/4964162/how-to -add-表列標題到SQL-select語句) – Dan 2014-09-03 16:55:16

回答

0

登錄電子,因爲它是另一種方式來解決問題:

從dual UNION中選擇'col_1','col_2','col_3','col_4'全部從table_1中選擇 col_1,col_2,col_3,col_4;

0

這是一個奇怪的問題:)嘗試

SELECT 
    * 
FROM 
    information_schema.COLUMNS 
where 
    table_chema = 'your_schema' 
     and table_name = 'your_table'; 

不是使用ORDINAL_POSITION這分別顯示相關的列名