John Humphreys
John Humphreys

Reputation: 39224

MySQL insert if a specific column doesn't have a specific value in it already

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.

Upvotes: 1

Views: 302

Answers (2)

Chris Santiago
Chris Santiago

Reputation: 415

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.

Upvotes: 1

krakover
krakover

Reputation: 3029

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

Upvotes: 2

Related Questions