Choose if there are other inserts?

IF EXISTS (select * from users where username = 'something') THEN select id from users where username = 'something'; ELSE insert into users (username) values ('something'); END IF; 
+2
source share
2 answers

Your expression is fine. The only problem is that you cannot use it as a regular request. Control structures such as IF or WHILE are only allowed in stored procedures or functions.

Just create a procedure like this:

 delimiter $$ create procedure select_or_insert() begin IF EXISTS (select * from users where username = 'something') THEN select id from users where username = 'something'; ELSE insert into users (username) values ('something'); END IF; end $$ 

and name it as follows:

 call select_or_insert(); 

What is it.

+9
source

You can try the following: -

 if exists( select * from mytable where field = 'something') begin select somefield from mytable where field = 'something'; end else begin insert into users (username) values ('something'); end 

or

 if not exists( select * from mytable where field = 'something') begin insert into users (username) values ('something'); end else begin select somefield from mytable where field = 'something'; end 

Although both of the above requests are the same.

or try using this if:

 IF EXISTS (select * from mytable where users = 'something') select field from mytable where users = 'something' else into mytable (users) values ('something') 

Here is SQLFIDDLEDEMO

+1
source

All Articles