Usage of MySQL's “IF EXISTS”

前端 未结 5 1910
Happy的楠姐
Happy的楠姐 2020-11-22 13:25

Here are two statements that I\'d like to work, but which return error messages:

IF EXISTS (SELECT * FROM gdata_calendars WHERE `group` =  ? AND id = ?) SELE         


        
相关标签:
5条回答
  • 2020-11-22 13:39

    You cannot use IF control block OUTSIDE of functions. So that affects both of your queries.

    Turn the EXISTS clause into a subquery instead within an IF function

    SELECT IF( EXISTS(
                 SELECT *
                 FROM gdata_calendars
                 WHERE `group` =  ? AND id = ?), 1, 0)
    

    In fact, booleans are returned as 1 or 0

    SELECT EXISTS(
             SELECT *
             FROM gdata_calendars
             WHERE `group` =  ? AND id = ?)
    
    0 讨论(0)
  • 2020-11-22 13:45

    I found the example RichardTheKiwi quite informative.

    Just to offer another approach if you're looking for something like IF EXISTS (SELECT 1 ..) THEN ...

    -- what I might write in MSSQL

    IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='')
    BEGIN
        SELECT TableID FROM Table WHERE FieldValue=''
    END
    ELSE
    BEGIN
        INSERT INTO TABLE(FieldValue) VALUES('')
        SELECT SCOPE_IDENTITY() AS TableID
    END
    

    -- rewritten for MySQL

    IF (SELECT 1 = 1 FROM Table WHERE FieldValue='') THEN
    BEGIN
        SELECT TableID FROM Table WHERE FieldValue='';
    END;
    ELSE
    BEGIN
        INSERT INTO Table (FieldValue) VALUES('');
        SELECT LAST_INSERT_ID() AS TableID;
    END;
    END IF;
    
    0 讨论(0)
  • 2020-11-22 13:45
    if exists(select * from db1.table1 where sno=1 )
    begin
    select * from db1.table1 where sno=1 
    end
    else if (select * from db2.table1 where sno=1 )
    begin
    select * from db2.table1 where sno=1 
    end
    else
    begin
    print 'the record does not exits'
    end
    
    0 讨论(0)
  • 2020-11-22 13:47
    SELECT IF((
         SELECT count(*) FROM gdata_calendars 
         WHERE `group` =  ? AND id = ?)
    ,1,0);
    

    For Detail explanation you can visit here

    0 讨论(0)
  • 2020-11-22 13:54

    The accepted answer works well and one can also just use the

    If Exists (...) Then ... End If; 
    

    syntax in Mysql procedures (if acceptable for circumstance) and it will behave as desired/expected. Here's a link to a more thorough source/description: https://dba.stackexchange.com/questions/99120/if-exists-then-update-else-insert

    One problem with the solution by @SnowyR is that it does not really behave like "If Exists" in that the (Select 1 = 1 ...) subquery could return more than one row in some circumstances and so it gives an error. I don't have permissions to respond to that answer directly so I thought I'd mention it here in case it saves someone else the trouble I experienced and so others might know that it is not an equivalent solution to MSSQLServer "if exists"!

    0 讨论(0)
提交回复
热议问题