Does MySQL Short Circuit the IF() function?

前端 未结 4 959
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:36

    With J. Jorgenson's help I came up with my own test case. His example does not try to short circuit in the condition evaluation, but using his idea I came up with my own test and verified that MySQL does indeed short-circuit the IF() condition check.

    SET @var:=5;
    SELECT IF(1 = 0 AND (@var:=10), 123, @var); #Expected output: 5
    SELECT IF(1 = 1 AND (@var:=10), @var, 123); #Expected output: 10
    

    On the second example, MySQL is properly short-circuiting: @var never gets set to 10.

    Thanks for the help J. Jorgenson!

提交回复
热议问题