Heim  >  Fragen und Antworten  >  Hauptteil

Einbetten von Abfrageoperationen in MySQL-IF-Anweisungen

Gibt es eine Möglichkeit, eine Einfügeabfrage innerhalb einer IF-Anweisung auszuführen? Ich weiß, dass die Syntax für eine if-Anweisung

ist

IF(条件, 如果条件为真执行的语句, 如果条件为假执行的语句)

Meine Frage ist, ob es möglich ist, eine Einfügeanweisung basierend auf einer Bedingung wie

auszuführen

IF((从表中选择计数(*),其中 id = x) = 0, insert1, insert2)

insert1 ist eine direkte Einfügung, ähnlich wie

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

insert2 ruft den vorherigen Wert der ID ab, deren Anzahl nicht 0 ist, führt dann eine Logik aus und fügt schließlich die Abfrage ein, die wie folgt aussieht:

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

P粉155832941P粉155832941245 Tage vor404

Antworte allen(1)Ich werde antworten

  • 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;

    Antwort
    0
  • StornierenAntwort