Insert into a MySQL table or update if exists

前端 未结 11 2645
再見小時候
再見小時候 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:21

    In case, you want to keep old field (For ex: name). The query will be:

    INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE    
    name=name, age=19;
    
    0 讨论(0)
  • 2020-11-21 05:22

    Just because I was here looking for this solution but for updating from another identically-structured table (in my case website test DB to live DB):

    INSERT  live-db.table1
    SELECT  *
    FROM    test-db.table1 t
    ON DUPLICATE KEY UPDATE
            ColToUpdate1 = t.ColToUpdate1,
            ColToUpdate2 = t.ColToUpdate2,
            ...
    

    As mentioned elsewhere, only the columns you want to update need to be included after ON DUPLICATE KEY UPDATE.

    No need to list the columns in the INSERT or SELECT, though I agree it's probably better practice.

    0 讨论(0)
  • 2020-11-21 05:22

    In my case i created below queries but in the first query if id 1 is already exists and age is already there, after that if you create first query without age than the value of age will be none

    REPLACE into table SET `id` = 1, `name` = 'A', `age` = 19
    

    for avoiding above issue create query like below

    INSERT INTO table SET `id` = '1', `name` = 'A', `age` = 19 ON DUPLICATE KEY UPDATE `id` = "1", `name` = "A",`age` = 19
    

    may it will help you ...

    0 讨论(0)
  • 2020-11-21 05:24

    When using SQLite:

    REPLACE into table (id, name, age) values(1, "A", 19)
    

    Provided that id is the primary key. Or else it just inserts another row. See INSERT (SQLite).

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题