简体   繁体   中英

Condition with SELECT and INSERT statement in MySQL

i would like to make SELECT statement when the condition is equals to 1, so that will execute INSERT statement, when not, so it will not doing anything. What i think you can see below in my code.

SET @var = 1;

SELECT IF(@var = 1, 
    INSERT INTO tabulka VALUES('value1','name1'),
    0
)

Thanks

You just need an IF statement, not a SELECT.

if
    @var = 1
then
    insert into tabulka values('value1', 'name1');
end if

got it!

http://sqlfiddle.com/#!2/66b33/1/0

create table test (
    int_field int, 
    str_field varchar(10) 
  );


set @var := 1;

insert into test 
   select  int_field, str_field 
   from    (select @var as int_field,
                   concat('var=',@var) as str_field 
           ) as temp
   where   @var=3;


set @var := 3;

insert into test 
   select  int_field, str_field 
   from    (select @var as int_field,
                   concat('var=',@var) as str_field 
           ) as temp
   where   @var=3; 


select * from test; 

results in:

int_field      str_field
3              var=3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM