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
https://forums.phpfreaks.com/topic/133023-mysql-if-exists-update-else-insert/
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

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)

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.

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.