MySQL通過自增一列在Select ... into outfile...裡面實現CSV匯出帶欄位的效果

來源:互聯網
上載者:User

標籤:

CSV的範例中Select ... into outfile...是不帶欄位名的,只匯出資料,所以需要自己想另外的辦法實現,這裡有一個笨招,自己構造一個欄位列,樣本如下:

1,建立測試表資料
CREATE TABLE test.c SELECT 1 AS pid,1 AS item,15.0 AS wgt UNION ALL
SELECT 1 AS pid,2 AS item,20.0 AS wgt UNION ALL
SELECT 1 AS pid,3 AS item,30.0 AS wgt UNION ALL
SELECT 1 AS pid,4 AS item,29.0 AS wgt;
SELECT * FROM test.c;


mysql> SELECT * FROM test.c;
+-----+------+------+
| pid | item | wgt  |
+-----+------+------+
|   1 |    1 | 15.0 | 
|   1 |    2 | 20.0 | 
|   1 |    3 | 30.0 | 
|   1 |    4 | 29.0 | 
+-----+------+------+
4 ROWS IN SET (0.00 sec)


2,通過union all實現欄位列,並且排在第一行

SELECT * FROM (
SELECT ‘pid‘ AS pid,‘item‘ AS item,‘wgt‘ AS wgt
UNION ALL
SELECT * FROM test.c
)a INTO OUTFILE ‘/tmp/c.csv‘ 
 FIELDS TERMINATED BY ‘,‘ 
 OPTIONALLY ENCLOSED BY ‘"‘
  LINES TERMINATED BY ‘\n‘;

執行如下:
mysql> SELECT * FROM (
    -> SELECT ‘pid‘ AS pid,‘item‘ AS item,‘wgt‘ AS wgt
    -> UNION ALL
    -> SELECT * FROM test.c
    -> )a INTO OUTFILE ‘/tmp/c.csv‘ 
    ->  FIELDS TERMINATED BY ‘,‘ 
    ->  OPTIONALLY ENCLOSED BY ‘"‘
    ->   LINES TERMINATED BY ‘\n‘;
Query OK, 5 rows affected (0.00 sec)

3,去開啟c.csv檔案查看效果

MySQL通過自增一列在Select ... into outfile...裡面實現CSV匯出帶欄位的效果

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.