Does MySQL Short Circuit the IF() function?

前端 未结 4 963
Happy的楠姐
Happy的楠姐 2021-01-18 15:05

I need to query data from a second table, but only if a rare set of conditions in the primary table is met:

SELECT ..., IF(a AND b AND c AND (SELECT 1 FROM t         


        
4条回答
  •  礼貌的吻别
    2021-01-18 15:17

    The answer is YES.
    The IF(cond,expr_true,expr_false) within a mysql query is short-circuited.

    Here a test, using @variables to prove the fact:

    SET @var:=5;  
    SELECT IF(1 = 0, (@var:=@var + 1), @var ); -- using ':=' operator to modify 'true' expr @var 
    SELECT IF(1 = 1, @var, (@var:=@var + 1) ); -- using ':=' operator to modify 'false' expr @var 
    SELECT @var;
    

    The result is '5' from all three SELECT queries.

    Had the IF() function NOT short circuited, the result would be a '5' from SELECT #1, and '6' from SELECT #2, and a '7' from the last "select @var".

    This is because the 'true' expression is NEVER executed, in select #1 and nor is the false expression executed for select #2.

    Note the ':=' operator is used to modify an @var, within an SQL query (select,from, and where clauses). You can get some really fancy/complex SQL from this. I've used @vars to apply 'procedural' logic within a SQL query.

    -- J Jorgenson --

提交回复
热议问题