如果记录不存在,如何在mysql中插入?

时间:2014-07-19 08:20:03

标签: php mysql sql

我的数据库是

表格

        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已经存在于其列中,则不会插入

1 个答案:

答案 0 :(得分: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;

最好在字段上创建一个唯一的UNIQUE INDEX(new_id),然后使用:

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