Mysql CSV加载infile

时间:2012-12-23 17:06:39

标签: php mysql csv

我有一个包含9列的CSV文件,我有一个包含11列的MySQL表。

CSV文件如下所示:

col1, col2, col3, col4, col5, col6, col7, col8, col9

和MySQL表看起来像:

col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11

我需要让脚本忽略两个错误的(但必需的)MySQL列。

导入中需要忽略的mysql列是:db_id& nice_date =)

这是我到目前为止所做的:

$sql = 'LOAD DATA LOCAL INFILE "../csvtemp/test.csv" 
        INTO TABLE sample 
            FIELDS TERMINATED BY "," 
            OPTIONALLY ENCLOSED BY """" 
            IGNORE 1 LINES'
;

2 个答案:

答案 0 :(得分:4)

$sql = 'LOAD DATA LOCAL INFILE "../csvtemp/test.csv" 
        INTO TABLE sample 
            FIELDS TERMINATED BY "," 
            OPTIONALLY ENCLOSED BY """" 
            IGNORE 1 LINES
            (col1, col2, col3, col4, col5, col6, col7, col8, col9)'
;

缺少的列将被赋予其DEFAULT值,否则您可以这样指定固定值:

$sql = 'LOAD DATA LOCAL INFILE "../csvtemp/test.csv" 
        INTO TABLE sample 
            FIELDS TERMINATED BY "," 
            OPTIONALLY ENCLOSED BY """" 
            IGNORE 1 LINES
            (col1, col2, col3, col4, col5, col6, col7, col8, col9)'
            SET col10 = 'abc', col11 = 'xyz'
;

答案 1 :(得分:0)

您似乎可以使用LINES TERMINATED BY(也许使用PHP_EOLhttp://dev.mysql.com/doc/refman/5.0/en/load-data.html

引用手册页:

  

如果某行不包含所有字段,则设置其余列   到他们的默认值。