MySQL “good” way to insert a row if not found, or update it if it is found

后端 未结 6 1521
小蘑菇
小蘑菇 2020-12-08 11:44

Very often, I want to run a query on one of my users where I want a row stored and associated with that user, in a 1-to-1 relationship. So let\'s say (this is just an arbit

6条回答
  •  遥遥无期
    2020-12-08 12:11

    I think it's easier to switch it around. Try to insert, then update.

    MySQL specifically has a clause 'ON DUPLICATE KEY'

    INSERT INTO cars (fields) VALUES (values) ON DUPLICATE KEY UPDATE ...

    This of course requires you to have proper unique keys setup.

提交回复
热议问题