Insert into a MySQL table or update if exists

前端 未结 11 2644
再見小時候
再見小時候 2020-11-21 04:27

I want to add a row to a database table, but if a row exists with the same unique key I want to update the row.

For example:



        
11条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 05:26

    Try this:

    INSERT INTO table (id,name,age) VALUES('1','Mohammad','21') ON DUPLICATE KEY UPDATE name='Mohammad',age='21'

    Note:
    Here if id is the primary key then after first insertion with id='1' every time attempt to insert id='1' will update name and age and previous name age will change.

提交回复
热议问题