正在将 csv 加载到 mysql 选择列

Loading csv into mysql selecting columns

我正在努力学习如何有效地使用 mysql。现在,我想将包含作者参考书目的 csv 加载到 mysql 数据库中。这是我生成数据库并尝试上传文件的代码:

USE stephenkingbooks;

DROP TABLE IF EXISTS stephenkingbooks;
CREATE TABLE stephenkingbooks
(
  `id`              int unsigned NOT NULL auto_increment,
  `original_title`  varchar(255) NOT NULL,
  `spanish_title`   varchar(255) NOT NULL,
  `year`            decimal(4) NOT NULL,
  `pages`           decimal(10) NOT NULL,
  `in_collection`   enum('Y','N') NOT NULL DEFAULT 'N',
  `read`            enum('Y','N') NOT NULL DEFAULT 'N',

  PRIMARY KEY     (id)
);

LOAD DATA LOCAL INFILE '../files/unprocessed_sking.csv'
INTO TABLE stephenkingbooks (column1, column2, column4, column3)
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 ROWS;

csv文件格式如下:

Carrie,Carrie,Terror,199,19745,"En 1976, el director de cine Brian de Palma hizo la primera película basada en la novela.7 3"

我的想法是仅加载对应于 original_title 的前两列,第二列是西班牙文标题(在 mysql 和 csv 中相同),在 csv 中的第 3 列之后是 pages,第 4 列是 year

此外,对于年份列,我只想取该字段的前 4 个数字,因为其中一些引用不属于年份。例如,Carrie 于 1974 年发布,但 csv 在我不想考虑的日期中包含一个 5。

我的问题是我无法在我的终端中没有错误地获得我想要的东西...有什么建议吗?

13.2.6 LOAD DATA INFILE Syntax

...

You must also specify a column list if the order of the fields in the input file differs from the order of the columns in the table.

...

尝试:

mysql> LOAD DATA INFILE '../files/unprocessed_sking.csv'
    -> INTO TABLE `stephenkingbooks`
    -> FIELDS TERMINATED BY ','
    -> ENCLOSED BY '"'
    -> LINES TERMINATED BY '\r\n'
    -> (`original_title`, `spanish_title`, @`genre`, @`pages`, @`year`)
    -> SET `year` = LEFT(@`year`, 4), `pages` = @`pages`;
Query OK, 1 row affected (0.00 sec)
Records: 1  Deleted: 0  Skipped: 0  Warnings: 0

mysql> SELECT
    -> `id`,
    -> `original_title`,
    -> `spanish_title`,
    -> `year`,
    -> `pages`,
    -> `in_collection`,
    -> `read`
    -> FROM `stephenkingbooks`;
+----+----------------+---------------+------+-------+---------------+------+
| id | original_title | spanish_title | year | pages | in_collection | read |
+----+----------------+---------------+------+-------+---------------+------+
|  1 | Carrie         | Carrie        | 1974 |   199 | N             | N    |
+----+----------------+---------------+------+-------+---------------+------+
1 row in set (0.00 sec)