Author Topic: mysql conditional insert  (Read 1229 times)

ober

  • Ashton Shagger
  • Ass Wipe
  • Posts: 14310
  • Karma: +73/-790
  • mini-ober is taking over
    • Windy Hill Web Solutions
mysql conditional insert
« on: November 24, 2010, 10:15:10 PM »
In MySQL, is there a way to run a single query that will insert only if a key doesn't already exist?

The query keeps bitching at me for trying to put a WHERE clause on an INSERT but there has to be a better way than going to the database twice (select and check row count and then insert if 0), right?

Perspective

  • badfish
  • Jackass In Charge
  • Posts: 4635
  • Karma: +64/-22
    • http://jeff.bagu.org
Re: mysql conditional insert
« Reply #1 on: November 24, 2010, 11:09:43 PM »
What language are you calling it from? You should be able to catch the duplicate key error.

Mike

  • Jackass In Charge
  • Posts: 11257
  • Karma: +168/-32
  • Ex Asshole - a better and more caring person.
Re: mysql conditional insert
« Reply #2 on: November 24, 2010, 11:13:23 PM »
Ok, first, if the key exists do you want to update the non-key columns or fail?

If you want to update you can do a REPLACE INTO but this isn't always ideal as it'll delete the previous row and insert a new one.  You can also do a INSERT INTO ... ON DUPLICATE KEY UPDATE

If you want to just fail then use INSERT IGNORE