1

I read a few solutions on stack overflow and found this to be the closest to my question:

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

Basically, I'm creating an index of words (from websites) and one of my tables is just a primary key (integer id), and a varchar(35) word.

I need to be able to try and insert a new entry (basically, a new word) word into this table. If the word is not present, a new record with it will be added. If it is present, nothing will happen.

What's the best way to get this functionality? "REPLACE INTO" changes my keys which is not desirable - I'd just like it to be a no-op if mysql finds the word is already in the database table.

Community
  • 1
  • 1
John Humphreys
  • 37,047
  • 37
  • 155
  • 255

2 Answers2

2

Assuming you have a unique key on the word - using insert ignore might do the trick.

krakover
  • 2,989
  • 2
  • 27
  • 29
1

of the top of my head I think of:

if not exists(Select 1 from <Table> where word = 'theWord')
Begin
  --//do your insert
End

now this is in Sql Server so im not sure of the differences for MySql. let me know if this helps.

Chris Santiago
  • 415
  • 2
  • 8
  • Thanks for the try. I think this would work if I played around with it enough, but the syntax is a little off and the error wasn't obvious. The insert ignore idea works great for mysql though - personally, I'm an SQL server guy myself though too haha. – John Humphreys Oct 14 '11 at 21:05