让我们说MySQL
create table test_tbl
(
col1 varchar(100),
col2 varchar(100),
amount int,
created datetime
)
数据插入
Insert into test_tbl values('unu', 'doi', 10, '05/01/2015');
Insert into test_tbl values('patru', trei', 400, '04/01/2015');
我需要以下列格式导出该表中的所有数据。该文件应为txt文件。
"col1"="unu","col2"="doi","amount"="10","created"="05/01/2015"
"col1"="patru","col2"="trei","amount"="400","created"="04/01/2015"
所以逻辑是: 每个列名称的值用逗号分隔。
是否可以在MySQL
中获得此类结果?
答案 0 :(得分:1)
也许这可行。
使用Edge
构建一个像这样的字符串
CONCAT
然后您也可以使用SELECT
CONCAT('"col1"="',col1,'","col2"="',col2,'","amount"="',amount,'","created"="',created,'"') t
FROM test_tbl;
将其转储到文本文件中。
INTO OUTFILE
由于SELECT
CONCAT('"col1"="',col1,'","col2"="',col2,'","amount"="',amount,'","created"="',created,'"') t
FROM test_tbl
INTO OUTFILE 'C:/yourtextfile.txt'
CHARACTER SET latin1
FIELDS ENCLOSED BY ''
LINES TERMINATED BY '\r\n';
只有1行,因此您无需将任何列/字段包含在内,因为它们是自定义的。只有换行符用于终止每个CONCAT
。
希望它有效!
答案 1 :(得分:1)
用于导出表格的数据 -
SELECT CONCAT('"col1"="',col1,'","col2"="',col2,'","amount"="',amount,'","created"="',DATE_FORMAT(created,'%d/%m/%Y'),'"') t FROM test_tbl INTO OUTFILE '/tmp/test.txt' CHARACTER SET latin1 FIELDS ENCLOSED BY '' LINES TERMINATED BY '\r\n';
从csv导入表格
mysql> CREATE TABLE `test_tbl` (
-> `col1` varchar(100) DEFAULT NULL,
-> `col2` varchar(100) DEFAULT NULL,
-> `amount` int DEFAULT NULL,
-> `created` datetime DEFAULT NULL
-> ) ENGINE=InnoDB DEFAULT CHARSET=latin1
-> ;
Query OK, 0 rows affected (0.44 sec)
mysql> load data local infile 'test.txt' into table test_tbl fields terminated by ',' ENCLOSED BY '"' lines terminated by '\r\n' (@col1, @col2,@col3,@col4)
-> set col1 = substr(@col1,8), col2 = substr(@col2,8), amount = substr(@col3,10), created = str_to_date(substr(@col4,11), '%d/%m/%Y');
Query OK, 2 rows affected (0.09 sec)
Records: 2 Deleted: 0 Skipped: 0 Warnings: 0
mysql> select * from test_tbl;
+-------+------+--------+---------------------+
| col1 | col2 | amount | created |
+-------+------+--------+---------------------+
| unu | doi | 10 | 2015-01-05 00:00:00 |
| patru | trei | 400 | 2015-01-04 00:00:00 |
+-------+------+--------+---------------------+
2 rows in set (0.00 sec)