LOAD DATA INFILE,跳过表格中的第一列

时间:2013-12-11 13:35:40

标签: mysql csv

我无法找到将csv文件加载到表中的正确语法,同时跳过表中已存在的第一列。我的表格列如下所示:

ID    COL1    COL2    COL3    LOG_DATE

我的csv看起来像这样:

dataForCol1,dataForCol2,dataForCol3

所以我想将csv中的值加载到COL1 COL2和COL3中,跳过ID。我能得到的最接近的是这样的SQL:

LOAD DATA LOCAL INFILE 'test.csv'
INTO TABLE test_table
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n' 
(ID,COL1,COL2,COL3,LOG_DATE)
SET ID=0, LOG_DATE=CURRENT_TIMESTAMP

请注意,我不太了解SQL并且我不确定我是否正确使用了SET子句,但是此语句将为LOG_DATE列提供时间戳,并且它将自动增加{{ 1}}列(IDID)和type: int(11)但其他数据偏离一列,因此auto_incerement缺失,dataForCol1位于{ {1}}等等。

3 个答案:

答案 0 :(得分:10)

列列表应仅包含文件中的列:

LOAD DATA LOCAL INFILE 'test.csv'
INTO TABLE test_table
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n' 
(COL1,COL2,COL3)
SET LOG_DATE=CURRENT_TIMESTAMP

答案 1 :(得分:1)

只需将ID col移动到最后一个字段位置,如下所示:

EG: COL1    COL2    COL3    ID    LOG_DATE

然后使用相同的代码而不定义您的字段或ID:

LOAD DATA LOCAL INFILE 'test.csv'
INTO TABLE test_table
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n' 
SET LOG_DATE=CURRENT_TIMESTAMP

超级简单,效果很好。

答案 2 :(得分:0)

我能解决同样问题的唯一方法是创建一个临时表来加载所有数据,然后将该数据插入永久表中。我将它与多文件上传过程结合使用:

# Check for attempted file/s upload
if (isset($_FILES['files']))
{
    # Create a temporary table to insert data into
    $sql="CREATE TEMPORARY TABLE `Temp` (Region VARCHAR(60), First_Name VARCHAR(35), Last_Name VARCHAR(35), Title VARCHAR(60), Account_Name VARCHAR(60), Phone VARCHAR(21), Email VARCHAR(60));";
    $Result = mysql_query($sql,$MySQL_Read);

    # Loop through file/s to be uploaded
    foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name)
    {

        # Upload file
        move_uploaded_file($tmp_name, $Path."{$_FILES['files']['name'][$key]}");
        echo $Path."{$_FILES['files']['name'][$key]}<br>";

        # LOAD DATA from CSV file into Temp
        $sql="LOAD DATA INFILE '".$Path."{$_FILES['files']['name'][$key]}' INTO TABLE `Temp` FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '\\\\' LINES TERMINATED BY '\\r' STARTING BY '' IGNORE 1 LINES;";
        $Result = mysql_query($sql,$MySQL_Write);
        echo($sql.'<br><br>');

        # Delete file
        unlink($Path."{$_FILES['files']['name'][$key]}");
    }
}

# Insert data from temp table into permanent table
$sql="INSERT INTO `Leads` (`Region`, `First_Name`, `Last_Name`, `Title`, `Account_Name`, `Phone`, `Email`) SELECT `Region`, `First_Name`, `Last_Name`, `Title`, `Account_Name`, `Phone`, `Email` FROM `Temp`;";
$Result = mysql_query($sql,$MySQL_Write);

# Delete temporary table
$sql="DROP TEMPORARY TABLE Temp;";
$Result = mysql_query($sql,$MySQL_Write);