如果從包含 NULL 值的表中匯出資料到 CSV 檔案,我們如何儲存除 N 之外的任何其他值?


如果我們想在從包含 NULL 值的表中匯出資料到 CSV 檔案時,儲存 \N 之外的任何其他值,則需要使用 IFNULL 語句將 \N 值替換為其他值。為了說明這一點,我們來看下面的例子:

示例

假設我們想要匯出名為 ‘student_info’ 的表的值,該表包含以下資料:

mysql> Select * from Student_info;
+------+---------+------------+------------+
| id   | Name    | Address    | Subject    |
+------+---------+------------+------------+
| 101  | YashPal | Amritsar   | History    |
| 105  | Gaurav  | Chandigarh | Literature |
| 125  | Raman   | Shimla     | Computers  |
| 130  | Ram     | Jhansi     | Computers  |
| 132  | Shyam   | Chandigarh | Economics  |
| 133  | Mohan   | Delhi      | Computers  |
| 150  | Saurabh | NULL       | Literature |
+------+---------+------------+------------+
7 rows in set (0.00 sec)

我們可以看到,當 id 為 150 時,地址欄位的值為 NULL。下面的查詢將把該表的資料匯出到 Student_28.CSV 檔案中,並將 ‘Not Applicable’ 儲存在 \N 的位置:

mysql> Select IFNULL(id,'Not Applicable'), IFNULL(Name,'Not Applicable'), IFNULL(Address,'Not Applicable'), IFNULL(Subject,'Not Applicable') from Student_info INTO OUTFILE 'C:/mysql/bin/mysql-files/student_28.csv' FIELDS TERMINATED BY ',';
Query OK, 7 rows affected (0.02 sec)

我們可以看到,student_28.CSV 檔案中 \N 的位置被替換為 Not Applicable,如下面的值所示:

101   YashPal   Amritsar         History
105   Gaurav    Chandigarh       Literature
125   Raman     Shimla           Computers
130   Ram       Jhansi           Computers
132   Shyam     Chandigarh       Economics
133   Mohan     Delhi            Computers
150   Saurabh   Not Applicable   Literature

更新於: 2020年2月7日

173 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.