2013-12-11 65 views
3

我無法找到將csv文件加載到表的正確語法,同時跳過表中已存在的第一列。我的表列如下:LOAD DATA INFILE,跳過表中的第一列

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柱時間戳,它會自動遞增ID列(IDtype: int(11)和auto_incerement),但其他數據是關閉的一個列,以便dataForCol1失蹤,dataForCol2COL1

回答

10

列清單應iclude列僅在文件中:

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 
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); 
0

只需將您的ID欄移動到這樣的最後一個字段位置:

EG: COL1 COL2 COL3 ID LOG_DATE 

然後使用相同的代碼而不定義你的領域或編號:

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

超級簡單,效果很好。