希望我能够解释得这么好......我有一个名为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
中的值。
提前致谢!
答案 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)