在MySQL的IF語句中嵌入查詢操作
P粉155832941
P粉155832941 2024-02-17 16:44:15
0
1
392

是否有辦法在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粉155832941
P粉155832941

全部回覆(1)
P粉077701708

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

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;
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!