ANY answer.
Re: Insert or update a record if it already exists?
This is a variation that works for tables with multiple primary keys.
If you have a users table with columns of username, dept, and age, and primary keys of username and dept, then this will only insert a user if it doesn't exist already.
[sql]
INSERT INTO users (username, dept, age) SELECT username='mp', dept='tax', age=5 WHERE (SELECT COUNT (*) FROM users WHERE username='mp' AND dept='tax')=0;
[/sql]
I initially found this syntax confusing, but here's how I 'parsed' it.
This part returns 0 if it doesn't exist:
[sql]SELECT COUNT (*) FROM users WHERE username='mp' AND dept='tax'[/sql]
This part creates a record-like row with static values and represents the record to insert:
[sql]SELECT username='mp', dept='tax', age=5 [/sql]
The WHERE-clause following the above part will only return the value to insert if the count is 0.
|