Embedding query operations in MySQL IF statements
P粉155832941
P粉155832941 2024-02-17 16:44:15
0
1
424

Is there a way to run the insert query in an IF statement, I know the syntax of the if statement is

IF(condition, statement to be executed if the condition is true, statement to be executed if the condition is false)

My question is if it is possible to run an insert statement based on a condition, like

IF((Select count(*) from table where id = x) = 0, insert1, insert2)

insert1 will be a direct insert, similar to

Insert table (col1,col2..) value (val1,val2..)

insert2 will get the previous value of the id whose count is not 0, then do some logic and finally insert the query, which will look like

insert into table (col1, col2, col3..) select val1,val1 val2,someOperation from table where id = x;

P粉155832941
P粉155832941

reply all(1)
P粉077701708

I think you need something like this:

IF( select count(*) from Table1 ) is null
begin

    IF( select count(*) from Table1 ) is null
    begin
    --执行条件为真时的操作
    --插入条件
    end

    IF( select count(*) from Table1 ) is not null
    begin
    --执行条件为假时的操作
    --插入条件
    end

end

MYSQL example:

IF ((select count(*) from table where id = x)) = 0
        THEN 
         --插入到表中 (col1,col2..) values (val1, val2..)
        ELSE
             IF ((select count(*) from table where id = x)) != 0
             THEN 
             --插入到表中 (col1, col2, col3..) select val1,val1+val2,someOperation from table where id = x;
      END IF;
     END IF;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!