2012-08-29 85 views
0

我有一個表名爲system_settings的表,其中有3列,即IDActual_Setting & Standards_Setting將數據從文本文件導入到MySQL中的特定列中

ID列有3行,即'Virtual Machine 1''Virtual Machine 2' & 'Virtual Machine 3'

我希望從文本文件導入數據到列'Actual_Setting'其中ID = 'Virtual Machine 1'

我已經使用這個查詢嘗試:

LOAD DATA LOCAL IN FILE 'C:/Program Files/MySQL/MySQL Server 5.5/bin/syspolicy.txt' 
INTO system_settings(Actual_Setting) 
WHERE ID LIKE 'Virtual Machine 1'; 

但它返回一個錯誤。

我使用MySQL Server 5.5,MySQL查詢瀏覽器&是一臺Windows 7 PC。

回答

0

LOAD DATA將始終將數據插入新的行,而不會更新現有行。

但是,如果發生密鑰衝突,則可以通過使用其REPLACE關鍵字,先將刪除現有行。如果有對IDUNIQUE鍵,你並不需要保存的Standards_Setting值,你可以利用此功能優勢:

LOAD DATA LOCAL INFILE 'C:/Program Files/MySQL/MySQL Server 5.5/bin/syspolicy.txt' 
    REPLACE INTO TABLE system_settings 
    FIELDS TERMINATED BY '' ENCLOSED BY '' ESCAPED BY '' 
    LINES STARTING BY '' TERMINATED BY '' 
    (Actual_Setting) 
    SET ID = 'Virtual Machine 1' 

(注意,因爲要讀取整個文件轉換成單場,你必須重寫默認值,並明確規定,目前並無任何字段或行終止/報價/轉義字符)。

否則,如果您需要更新現有記錄,我建議您加載文件進入臨時表格,然後用內容更新您的表格:

CREATE TEMPORARY TABLE foo (content LONGTEXT); 

LOAD DATA LOCAL INFILE 'C:/Program Files/MySQL/MySQL Server 5.5/bin/syspolicy.txt' 
    INTO TABLE foo 
    FIELDS TERMINATED BY '' ENCLOSED BY '' ESCAPED BY '' 
    LINES STARTING BY '' TERMINATED BY '' 
    (content); 

UPDATE system_settings 
    SET Actual_Setting = (SELECT content FROM foo) 
WHERE ID = 'Virtual Machine 1'; 

DROP TEMPORARY TABLE foo; 
+0

@LamakDaruwala:我注意到你不接受這個答案;它沒有解決你的問題嗎? – eggyal

相關問題