简体   繁体   English

具有不同列的多个CSV到MySQL

[英]Multiple CSV to MySQL with Different Columns

I use the "load data infile" statement to load multiple .csv files in one table with a foreach loop. 我使用“ load data infile”语句通过foreach循环将多个.csv文件加载到一个表中。 This works, only I have one problem. 这有效,只有我有一个问题。 The columns in de .csv's are not the same. .csv中的列不相同。 For example I have this: 例如我有这个:

CSV1: CSV1:

id,name,ean,description id,名称,ean,描述

CSV2: CSV2:

id,name,image,ean,description id,名称,图像,ean,描述

And my MySQL table is: 我的MySQL表是:

id,name,ean,description id,名称,ean,描述

So because I want to import multiple csv's through a loop, I have a problem with CSV2, because of the image column. 因此,由于我想通过循环导入多个csv,因此由于image列,CSV2出现了问题。 If possible, I want to match the name of the csv column with the name of the table column. 如果可能,我想将csv列的名称与表列的名称匹配。 So in this example, [image] is not imported. 因此,在此示例中,未导入[image]。 I can use a @ignore variable, but because every .csv is different, this doesn't work. 我可以使用@ignore变量,但是由于每个.csv都不相同,因此无法正常工作。 I have this: 我有这个:

$sql = "
   LOAD DATA LOCAL INFILE '$value[path]'
       INTO TABLE db1.shoptest
       FIELDS TERMINATED BY '$value[seperator]'
       OPTIONALLY ENCLOSED BY '\"'
       LINES TERMINATED BY '\n'
     (id, name, ean, description)
    ;";

Is it possible to match the csv column names with the table column names and skip all other columns in the .csv? 是否可以将csv列名与表列名匹配,并跳过.csv中的所有其他列?

Thanks so much for helping me out! 非常感谢您的帮助!

Kind regards, Mark 亲切的问候,马克

I think I understood the question. 我想我明白这个问题。 You wan't to get the column headers from the first row of the CSV, then build a string to use as the col_name_or_user_var argument of LOAD DATA and use @ignore variable assignments as needed. 您不会从CSV的第一行获取列标题,而是构建一个字符串用作LOAD DATA的col_name_or_user_var参数,并根据需要使用@ignore变量分配。

id, name, state, ean, favorite_color, description

becomes... 变成...

(id, name, @bunk, ean, @bunk, description)

$whiteList = ['id', 'name', 'ean', 'description'];
$columnHeader = 'id, name, state, ean, favorite_color, description';
$columnHeader = explode(',', $s);
foreach ($columnHeader as $k => $v) {
    if (! in_array(trim($v), $whiteList)) $columnHeader[$k] = '@bunk';

}

echo implode(',', $columnHeaders);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM