I need to run a query with an if else statement(if possible in MYSQL)
I want to: SELECT id FROM user_name_table WHERE user_name = @name;
If the result of the query returns null i want to insert @name to user_name_table and get the autoincrement generated id i need to store this result in a variable to use it later in another insert query.
This is as far as i got, in this case if “Sam” exists will return the ID twice, if not it will return ID and ‘0’
SET @name = "Sam"; SELECT id, IF(id!=0, id, 0) FROM user_name WHERE user_name = @name;
Advertisement
Answer
If you don’t want duplicates for name
, then add a unique constraint or index:
alter table user_name add constraint unq_user_name_name unique (name);
Then, if you want to insert a new name, you can simply use:
insert into user_name (name) values (@name);
This will return an error if there is a duplicate. If you don’t want an error, I would suggest:
insert into user_name (name) values (@name) on duplicate key update name = values(name);