2011-09-19 52 views
0

我有一個PHP file,它讀取一個CSV文件並將這些值存儲到SQL表中。mysql查詢幫助 - REPLACE INTO?

的SQL表有4列

id - primary key (just auto incremented integer) 
name - text value of an object name 
type - an integer value representing the type of object 
active - a bool to set if the object is active 

問題是CSV file不存儲ID,只是名稱和類型。

我想要做以下事情,並想知道做什麼最好的方法是用最少量的查詢。

設置active to 0在表

For each entry in the CSV 
if (name and type already exists in table) 
    set active to 1 
else 
    add new entry to the table 

return the id for the existing or new entry 

任何幫助將是每個條目不勝感激

感謝

  • 只是一個說明,它只是在MySQL的查詢後,我是,不是php代碼等...

回答

1

假設喲ü正在使用MySQL:

首先,你必須創建2場「獨一無二」的指標:nametype(這是一個索引不是兩個)

然後使用此查詢插入您的數據:

INSERT INTO `table` (`name`,`type`,`active`) VALUES ($name,$type,0) 
    ON DUPLICATE KEY UPDATE active = 1 

爲了得到你只是查詢其ID(聰明的辦法 - mysql_insert_id()不能與INSERT,UPDATE工作)

 
SELECT id FROM `table` WHERE `name`= '$name' AND `type` = '$type' 
+0

喜izeed,非常感謝,我不知道我可以ç創建一個具有多個值的唯一鍵。 –