0

I need to do a such thing in SQL but I don't know how...

IF *row exists* THEN  
  UPDATE ...
ELSE
 CREATE ...

I can't figure how to do that..

1
  • Your question is very undefined. Is this if a record already exists in a table then update the record; or is it create a table if the table doesn't exist? Commented Jun 20, 2011 at 2:53

2 Answers 2

4

INSERT ... ON DUPLICATE KEY UPDATE.... or REPLACE should do the trick:

ON DUPLICATE KEY UPDATE http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

REPLACE http://dev.mysql.com/doc/refman/5.0/en/replace.html

Sign up to request clarification or add additional context in comments.

2 Comments

INSERT INTO lang (ip, lang) VALUES('$ip', 'fr') ON DUPLICATE KEY UPDATE SET lang='fr' WHERE ip='$ip'; This doesn't seem to work.
@user576488, this should be INSERT INTO lang (ip, lang) VALUES('$ip', 'fr') ON DUPLICATE KEY UPDATE lang='fr'. This also requires a collision of the unique keys on the table. What's your table structure look like?
0

You can use a normal insert statement with a ON DUPLICATE KEY UPDATE described in the docs :

here http://dev.mysql.com/doc/refman/5.0/en/insert.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.