有没有办法从CSV文件加载数据,其中第一行是COLUMN名称,其他行是数据?
我尝试了简单的查询,但是它没有任何排序即可插入
查询:
$q = "LOAD DATA LOCAL INFILE '".$filepath.$filename_update."'
INTO TABLE ".$dbName.$tableName."_uimport_update
FIELDS TERMINATED BY ';'
ENCLOSED BY '\"'
IGNORE 1 LINES;";
数据库列
product_id, product_sku, ...
CSV文件
mdate, product_sku, ....
不良结果:
product_id, product_sku, ...
mdate, product_sku, ....
想要的结果:
product_id, product_sku, ...
product_id, product_sku, ....
答案 0 :(得分:1)
您可以指定查询中列的顺序。我建议向查询中添加一个字符集,并为机箱添加一个“可选”。
但让我们看看:
CREATE TABLE `foo` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`bar` varchar(255) DEFAULT NULL,
`baz` varchar(255) DEFAULT NULL,
`bla` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
vagrant @ fancyhost:〜$ cat foo.csv
bar; baz; bla
“ test bndg”; baaaaaaaaaaaaz;“ yeyo”
“我喜欢伪数据”;调试;虚拟
test1; test2; test3
mysql> LOAD DATA INFILE '/home/vagrant/foo.csv' INTO TABLE foo CHARACTER SET utf8 FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '"' IGNORE 1 LINES (bar,baz,bla)
-> ;
Query OK, 3 rows affected (0.01 sec)
Records: 3 Deleted: 0 Skipped: 0 Warnings: 0
mysql> SELECT * FROM foo;
+----+-------------------------+----------------+-------+
| id | bar | baz | bla |
+----+-------------------------+----------------+-------+
| 1 | test bndg | baaaaaaaaaaaaz | yeyo |
| 2 | I looooooove dummy data | debug | dummy |
| 3 | test1 | test2 | test3 |
+----+-------------------------+----------------+-------+
3 rows in set (0.00 sec)
mysql> LOAD DATA INFILE '/home/vagrant/foo.csv' INTO TABLE foo CHARACTER SET utf8 FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '"' IGNORE 1 LINES (bar,bla,baz)
-> ;
Query OK, 3 rows affected (0.01 sec)
Records: 3 Deleted: 0 Skipped: 0 Warnings: 0
mysql> SELECT * FROM foo;
+----+-------------------------+----------------+----------------+
| id | bar | baz | bla |
+----+-------------------------+----------------+----------------+
| 1 | test bndg | baaaaaaaaaaaaz | yeyo |
| 2 | I looooooove dummy data | debug | dummy |
| 3 | test1 | test2 | test3 |
| 4 | test bndg | yeyo | baaaaaaaaaaaaz |
| 5 | I looooooove dummy data | dummy | debug |
| 6 | test1 | test3 | test2 |
+----+-------------------------+----------------+----------------+
6 rows in set (0.00 sec)
您可以根据自己的示例轻松更改顺序:)