仅将第二列CSV导入MySQL

时间:2017-11-09 19:52:20

标签: mysql csv import

我想将CSV文件的第二列导入MySQL。这是CSV文件:

Name,Source,Follows
John,Youtube,Y
Kat,FB,N
Jacob,Twitter,N

这是我到目前为止的代码:

DROP TABLE temp;

CREATE TABLE temp
(ID          INT               AUTO_INCREMENT          primary key,
sn           VARCHAR(50)
);

DESCRIBE temp;

LOAD DATA LOCAL INFILE '/Users/...temp.csv' INTO TABLE Person
FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'
IGNORE 1 LINES
(@col2) set sn=@col2;

SELECT * FROM temp;

然而,我知道有一个空集。

1 个答案:

答案 0 :(得分:0)

尝试:

档案:/path/to/temp.csv

Name,Source,Follows
John,Youtube,Y
Kat,FB,N
Jacob,Twitter,N

MySQL命令行:

mysql> DROP TABLE IF EXISTS `temp`;
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE IF NOT EXISTS `temp` (
    ->   `ID` INT AUTO_INCREMENT PRIMARY KEY,
    ->   `sn` VARCHAR(50)
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> LOAD DATA LOCAL INFILE '/path/to/temp.csv'
    -> INTO TABLE `temp`
    ->   FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'
    ->   IGNORE 1 LINES
    ->   (@`null`, `sn`, @`null`);
Query OK, 3 rows affected (0.00 sec)
Records: 3  Deleted: 0  Skipped: 0  Warnings: 0

mysql> SELECT `ID`, `sn`
    -> FROM `temp`;
+----+---------+ 
| ID | sn      |
+----+---------+
|  1 | Youtube |
|  2 | FB      |
|  3 | Twitter |
+----+---------+
3 rows in set (0.00 sec)

<强>更新

mysql> LOAD DATA LOCAL INFILE '/tmp/temp.csv'
    -> INTO TABLE `temp`
    ->   FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'
    ->   IGNORE 1 LINES
    ->   (@`null`, `sn`);
Query OK, 3 rows affected, 3 warnings (0.00 sec)
Records: 3  Deleted: 0  Skipped: 0  Warnings: 3

mysql> SHOW WARNINGS;
+---------+------+---------------------------------------------------------------------------+
| Level   | Code | Message                                                                   |
+---------+------+---------------------------------------------------------------------------+
| Warning | 1262 | Row 1 was truncated; it contained more data than there were input columns |
| Warning | 1262 | Row 2 was truncated; it contained more data than there were input columns |
| Warning | 1262 | Row 3 was truncated; it contained more data than there were input columns |
+---------+------+---------------------------------------------------------------------------+
3 rows in set (0.00 sec)

mysql> SELECT `ID`, `sn`
    -> FROM `temp`;
+----+---------+
| ID | sn      |
+----+---------+
|  1 | Youtube |
|  2 | FB      |
|  3 | Twitter |
+----+---------+
3 rows in set (0.00 sec)