MySql: if value exists UPDATE else INSERT

前端 未结 4 2298
花落未央
花落未央 2020-12-04 23:08

I have some code that looks like this. There is also an autoincrement field in the table that I must retain (it is used in other tables). I would like to simplify and opti

4条回答
  •  离开以前
    2020-12-04 23:37

    How about REPLACE INTO:

    REPLACE INTO models
    ( col1, col2, col3 )
    VALUES
    ( 'foo', 'bar', 'alpha' )
    

    Assuming col1 is your primary key, if a row with the value 'foo' already exists, it will update the other two columns. Otherwise it will insert a new row.

提交回复
热议问题