MySQL 如何在屏幕上以CSV格式输出MySQL查询结果,而不是写入文件
要以CSV格式输出MySQL查询结果,使用concat()函数。语法如下 −
mysql> select concat(StudentId,',',StudentName,',',StudentAge) as CSVFormat from CSVFormatOutputs;
要理解上述语法,让我们创建一个表。创建表的查询如下−
mysql> create table CSVFormatOutputs
-> (
-> StudentId int not null auto_increment,
-> StudentName varchar(20),
-> StudentAge int,
-> PRIMARY KEY(StudentId)
-> );
Query OK, 0 rows affected (1.15 sec)
使用插入命令将一些记录插入表中。查询如下−
mysql> insert into CSVFormatOutputs(StudentName,StudentAge) values('Mike',23);
Query OK, 1 row affected (0.26 sec)
mysql> insert into CSVFormatOutputs(StudentName,StudentAge) values('John',26);
Query OK, 1 row affected (0.19 sec)
mysql> insert into CSVFormatOutputs(StudentName,StudentAge) values('Sam',19);
Query OK, 1 row affected (0.20 sec)
mysql> insert into CSVFormatOutputs(StudentName,StudentAge) values('Carol',27);
Query OK, 1 row affected (0.59 sec)
mysql> insert into CSVFormatOutputs(StudentName,StudentAge) values('Bob',24);
Query OK, 1 row affected (0.15 sec)
使用select语句显示表中的所有记录。查询如下−
mysql> select *from CSVFormatOutputs;
以下是输出结果−
+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
| 1 | Mike | 23 |
| 2 | John | 26 |
| 3 | Sam | 19 |
| 4 | Carol | 27 |
| 5 | Bob | 24 |
+-----------+-------------+------------+
5 rows in set (0.00 sec)
下面是使用concat()函数在屏幕上以CSV(逗号分隔值)格式获取输出的MySQL查询语句−
mysql> select concat(StudentId,',',StudentName,',',StudentAge) as CSVFormat from CSVFormatOutputs;
以下是显示CSV格式记录的输出−
+------------+
| CSVFormat |
+------------+
| 1,Mike,23 |
| 2,John,26 |
| 3,Sam,19 |
| 4,Carol,27 |
| 5,Bob,24 |
+------------+
5 rows in set (0.00 sec)
阅读更多:MySQL 教程
极客教程