Mr. B.
Mr. B.

Reputation: 8717

MySQL: what's the best way to insert if not exists?

I know there are a lot of threads about INSERT/UPDATE, but I didn't find a solution for my problem.

I've two tables to manage options:

# table 1: option_fields
id | label | type | default

# table 2: option_values
id | field_id | user_id | value

Note: field_id and user_id should be foreign-keys but they aren't.

I would like to insert into option_values if the entry does not exist, pseudeo code:

IF (field_id != 1 AND user_id != 2):
    INSERT 
      INTO option_values (field_id, user_id, value) 
    VALUES (1, 2, "text")
ELSE:
    UPDATE option_values
       SET value = "text"
     WHERE field_id = 1 AND user_id = 2
ENDIF;

The ways I know:

#1: ON DUPLICATE KEY Doesn't work because the only primary keys are "id"

#2: REPLACE I don't want to use REPLACE because I think its a dirty way (the primary keys will counted up everytime somebody changes his options).

#3: MySQL IF, THEN Uses too much performance and seems to be dirty as well.

What kind of solution would you choose and why? I guess #1 is the best one but I'm not possible to use it.

Thanks in advance!

Upvotes: 0

Views: 152

Answers (1)

Eugen Rieck
Eugen Rieck

Reputation: 65342

While id is the primary (and only unique) key, you definitly use the combination of field_id and user_id in a unique key role.

This suggests, that the cleanest solution would be to create a unique key on (field_id, user_id) and proceed with ON DUPLICATE KEY UPDATE

Upvotes: 1

Related Questions