首頁  >  問答  >  主體

在MySQL的IF語句中嵌入查詢操作

是否有辦法在IF語句中執行插入查詢,我知道if語句的語法是

IF(條件, 如果條件為真執行的語句, 如果條件為假執行的語句)

#我的問題是是否可以依照條件執行插入語句,例如

IF((從表格中選擇計數(*),其中 id = x) = 0, insert1, insert2)

insert1將是一個直接插入,類似於

插入表(col1,col2..)值(val1,val2..)

#insert2將取得計數不為0的id的先前值,然後進行一些邏輯操作,最後插入查詢,看起來像

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

#
P粉155832941P粉155832941244 天前403

全部回覆(1)我來回復

  • P粉077701708

    P粉0777017082024-02-18 15:07:07

    我認為你需要像這樣的東西:

    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範例:

    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;

    回覆
    0
  • 取消回覆