负载数据传输 - 拼命地被困住

时间:2014-01-31 12:04:47

标签: mysql sql load-data-infile

希望我能够解释得这么好......我有一个名为artists的表格,基本上有2列, artist_pk (主键)和 {{ 1}} 即可。我使用artist_name通过CSV文件将artist_name列的记录导入到表artists,并让MySQL提供LOAD DATA INFILE值。这一切都已完成。

现在我想为我的名为artist_pk的表导入数据(通过相同的导入方法)。这里的三个相关列是 albums (主要), album_pk album_name (外键)来自artist_pk表)。同样,我将让mySQL分配artists值。

在我的CSV数据中,我有album_name和artist_name。我没有artist_pk值。所以我的问题是:我可以将artist_name CSV列作为album_pk导入的一部分导入,而不是按原样使用,指示mySQL使用关联的 tables PRIMARY来自artist_pk表的键值?

e.g。 artists表中的记录:

artists

现在摘录我的CSV文件(我想把它放在我的artist_pk | artist_name | +-----------+--------------+ | 1 | Depeche Mode | +-----------+--------------+ 表中)。

albums

'Violator'将填充album_name artist_name Violator Depeche Mode 。但要填充albums.album_name,我希望MySQL使用albums.artist_pk中的'Depeche Mode'来获取其关联的artists.artist_name值(在这种情况下为1) - 这是表artist_pk中的值。

提前致谢!

1 个答案:

答案 0 :(得分:2)

假设已填充artists表,您可以利用SET中的会话变量和LOAD DATA INFILE子句在加载数据时进行必要的查找

LOAD DATA INFILE '/path/to/albums.txt'
INTO TABLE albums
FIELDS TERMINATED BY '\t' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(album_name, @artist_name) -- use a session variable to store a value read from the file
SET artist_pk = 
(
  SELECT artist_pk 
    FROM artists
   WHERE artist_name = @artist_name -- use a session variable to get an artist_pk
   LIMIT 1 -- this is to ensure that only one row will be returned
) 

让我们试一试

mysql> CREATE TABLE artists (`artist_pk` int not null auto_increment primary key, `artist_name` varchar(12));
Query OK, 0 rows affected (0.07 sec)

mysql> INSERT INTO artists (`artist_name`) VALUES ('Depeche Mode');
Query OK, 1 row affected (0.00 sec)

mysql> CREATE TABLE albums (`album_pk` int not null auto_increment primary key, album_name varchar(255), artist_pk int, foreign key (artist_pk) references artists(artist_pk));
Query OK, 0 rows affected (0.03 sec)

mysql> LOAD DATA INFILE '/tmp/albums.txt'
    -> INTO TABLE albums
    -> FIELDS TERMINATED BY '\t' OPTIONALLY ENCLOSED BY '"'
    -> LINES TERMINATED BY '\n'
    -> IGNORE 1 LINES
    -> (album_name, @artist_name)
    -> SET artist_pk = 
    -> (
    ->   SELECT artist_pk
    ->     FROM artists
    ->    WHERE artist_name = @artist_name
    -> );
Query OK, 1 row affected (0.01 sec)
Records: 1  Deleted: 0  Skipped: 0  Warnings: 0

mysql> select * from albums;                                                                                       
+----------+------------+-----------+
| album_pk | album_name | artist_pk |
+----------+------------+-----------+
|        1 | Violator   |         1 |
+----------+------------+-----------+
1 row in set (0.00 sec)