Friday 15 January 2010

mysql - Correct way of inserting new row into SQL table, but only if pair does not exist -



mysql - Correct way of inserting new row into SQL table, but only if pair does not exist -

this has been discussed before, cannot understand answers have found.

essentially have table 3 columns memo, user , keyid (the lastly 1 primary , auto_inc). insert pair of values (memo , user). if seek insert same pair 1 time again should not happen.

from found out, methods depend on unique key (which i've got, in keyid) don't understand still need sec query keyid of existing couple (or nothing, in case go ahead insertion).

is there way of in single query? or understanding i've read (using replace or ignore) wrong?

you need set unique key on user + memo,

alter table mytable add together constraint unique_user_memo unique (memo,user)

and using insert ignore or replace according needs when inserting. current unique key primary key, , good, need 2nd 1 in order not allow insertion of duplicate data. if not create new unique key on 2 columns together, you'll need select query before every insert check if pair exists.

mysql

No comments:

Post a Comment