如果我们将数据从包含 NULL 值的表导出到 CSV 文件,我们如何在 CSV 文件中存储除 N 之外的任何其他值?

mysqlmysqli database更新于 2025/5/22 12:28:17

如果我们想在将数据从包含 NULL 值的表导出到 CSV 文件时在 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 的 address 字段的值为 NULL。现在,以下查询将把该表的数据导出到 Student_28.CSV 中,并在 \N − 处存储 ‘Not Applicable’

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

相关文章


有用资源