我目前正在使用mysql LOAD DATA INFILE
將csv值插入名爲test
的表中。當事情變得更加複雜時,到目前爲止所有的東西都非常好。我有另一個表occupations
其中包含occupation_id
我正在使用test
表中的外鍵。原始csv文件僅帶有以下字段First Name
,Last Name
,Age
,Date Of Birth
和Occupation
(請參閱下面的示例值)。我想根據csv文本字段Occupation
來計算occupation_id
。這怎麼可能?在csv file
表字段值和外鍵 - LOAD DATA INFILE
列標題各自的價值
+------------+-----------+-----+---------------+------------+
| First Name | Last Name | Age | Date of Birth | Occupation |
+------------+-----------+-----+---------------+------------+
| Lionel | Messi | 27 | 6/24/1987 | Soccer |
| Michael | Jordan | 51 | 2/17/1963 | Basketball |
| Lebron | James | 30 | 12/30/1984 | Actor |
+------------+-----------+-----+---------------+------------+
表occupation
+---------------+-----------------+
| occupation_id | occupation_name |
+---------------+-----------------+
| 1 | Basketball |
| 2 | Soccer |
| 3 | Actor |
+---------------+-----------------+
結果CSV後插入到表test
+------------+-----------+-----+-------------+---------------+-----------------+
| first_name | last_name | age | dob | occupation_id | occupation_name |
+------------+-----------+-----+-------------+---------------+-----------------+
| Lionel | Messi | 27 | 1987-06-24 | 2 | Soccer |
| Michael | Jordan | 51 | 1963-02-17 | 1 | Basketball |
| Lebron | James | 30 | 1984-30-12 | 3 | Actor |
+------------+-----------+-----+-------------+---------------+-----------------+
PHP/SQL - 我的查詢到目前爲止
$db_insert = $db_con->prepare("LOAD DATA LOCAL INFILE '".$filename."'
INTO TABLE test FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(@column1, @column2, @column3, @column4, @column5)
SET [email protected], [email protected], [email protected], dob = STR_TO_DATE(@column4, '%m/%d/%Y'), [email protected]
");
$db_insert->execute();
+1這是一個很好的方法。如果在'LOAD DATA'中完成所有操作,我會得到以下錯誤:'SQLSTATE [42S22]:未找到列:1054'字段lis'中的未知列'occupation_name' –
我編輯了上述希望匹配列名上市。 –