2014-07-19 131 views
-4

我的數據庫是如果記錄不存在,如何在mysql中插入?

 id | new_id | affiliate_id | s_percent | a_percent | date 
     ---+---------+----------------+-----------+-----------+-------------- 
     32 | 970 |  34   |  0.25 | 0.2  | 1404387120 
     33 | 972 |  29   |  0.25 | 0.2  | 1404482095 
     34 | 973 |  26   |  0.25 | 0.33 | 1405752775 

,我想在這裏插入新的記錄。如果new_id在其列已經存在,那麼它不插入

+4

概念,你將需要:'primary_key'它不是'db'它是你的'表structure'。並請看看:http://stackoverflow.com/questions/913841/mysql-conditional-insert –

+0

是的,這是我的表..以及我應該怎麼做在這種情況下? – user3214124

+0

如果我理解正確,你需要'new_id'列的唯一鍵,以確保'new_id'中有唯一值...因此,如果'new_id'值已經在表中,插入將不會插入該行 –

回答

0

這不是一個好辦法,但是如果您堅持這樣做,您可以使用以下代碼:

INSERT INTO table_listnames (id,new_id,affiliate_id,s_percent,a_percent,date) 
SELECT * FROM (SELECT 34,973,26,0.25,0.33,1405752775) AS tmp 
WHERE NOT EXISTS (
    SELECT new_id FROM table_listnames WHERE new_id = '970' 
) LIMIT 1; 

這將是更好的創建領域應該是唯一的(NEW_ID)一UNIQUE INDEX,然後使用:

normal INSERT (and handle the error if the new_id already exists), 
INSERT IGNORE (which will fail silently cause a warning (instead of error) if new_id already exists) 
INSERT ... ON DUPLICATE KEY UPDATE 
相關問題