| |||
| MySQL has a special construct for this. Assume the 'username' column below is UNIQUE: INSERT INTO users (username, email) VALUES ('Jo', 'jo@email.com')The 'ON DUPLICATE KEY' statement only works on PRIMARY KEY and UNIQUE columns. |
| |||
| How about this: IF (EXISTS (SELECT * FROM AA_TestTable AS t1 |
| |||
INSERT INTO users (username)I use this method a lot. Obviously, 'Jo' would usually either be a variable or a field selected from another table. |
| |||
| This opption worked wonders! Thanks for posting |
| |||
| Quote:
You should be VERY CAREFUL with things like this. If you can't afford to set the transaction isolation level to SERIALIZABLE, some other transaction could add the row with ord_num='FFF' after you've tested for its existence, but before you've inserted it. This way you end up with violated primary constraint and error in one of these transactions. |
| |||
| 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. 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;I initially found this syntax confusing, but here's how I 'parsed' it. This part returns 0 if it doesn't exist: SELECT COUNT (*) FROM users WHERE username='mp' AND dept='tax'This part creates a record-like row with static values and represents the record to insert: SELECT username='mp', dept='tax', age=5The WHERE-clause following the above part will only return the value to insert if the count is 0. |







No comments:
Post a Comment