Jump to content

MySQL, IF EXISTS, UPDATE, ELSE INSERT?


aximbigfan

Recommended Posts

Hi,

 

I have a MySQL table with 3 colums.

1 is "dir"

2 is "key"

and 3 is the actual data.

 

I want to make an IF/Then system something like this (although this is not proper SQL, obviously)

if (exists (where dir='123' AND where key='456')

insert into...

else

update

 

How would I do this?

 

Thanks,

Chris

 

Link to comment
Share on other sites

OMG MANS YOU HAD CAPS SO I SHOULD PROBABLY RESPOND QUICKLY!!!!

 

 

 

Anyway, UPDATE INTO.

 

 

Or two separate queries.

I used caps because that's how I have seen SQL commands formatted, not because I need a quick answer. In fact, I am in no hurry.

 

Thanks for your help,

 

Chris

Link to comment
Share on other sites

It's MySQL isn't it?

If so, there's this useful syntax

 

INSERT INTO table (column1, column2) VALUES (value1, value2) ON DUPLICATE KEY UPDATE SET column1 = value1, column2 = value2...

 

But you have to have a UNIQUE index in that table for that to work (note: PRIMARY is UNIQUE)

Link to comment
Share on other sites

OMG MANS YOU HAD CAPS SO I SHOULD PROBABLY RESPOND QUICKLY!!!!

 

 

 

Anyway, UPDATE INTO.

 

 

Or two separate queries.

I used caps because that's how I have seen SQL commands formatted, not because I need a quick answer. In fact, I am in no hurry.

 

Thanks for your help,

 

Chris

Haha, nice one corbin you silly fool. LOL.

 

Why don't you just run separate queries? Run a query to check if it exists, if it does, insert, else update.

 

 

It's the only all caps title on the page.  Kinda stood out.

Link to comment
Share on other sites

All:

 

It looks like I will have to run 2 separate queries. I hate doing that, but it is the only way, I think.

 

I attempted ON DUPLICATE KEY, but it doesn't work because it isn't a _full_ duplicate if the data is changed, but the "dir" and "key" columns are kept the same.

 

Chris

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.