Max Plays
Max Plays

Reputation: 13

Insert into SQL if entry does not exist

I want to insert a row into my database table if the value of the first column does not exist in the table.

Example:

Name   Value1    Value2
------------------------    
John      2        3
Max       4        6
Alex      0        0

Now I want to insert a new person with the values 0 and 0 but only if the person does not exist. For example if I tried to insert John it would not do anything. All of this should happen in one single query.

Can anyone help?

Regards, Max

Upvotes: 0

Views: 171

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1271111

You can create a unique index on table(name) and then use insert ignore or insert on duplicate key update:

create unique index unq_t_name on t(name);

insert into t(name, value1, value2)
    values ($Name, $value1, $value2)
    on duplicate key update name = values(name);

The on duplicate key is a non-operation -- it does nothing if the name is already in the database.

Upvotes: 3

nicomp
nicomp

Reputation: 4657

Create an index on Name, make it unique. Thereafter you will not be able to add records where the name is already in there.

Upvotes: 1

Related Questions