Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to SET multiple user variables inside IF on MySQL

Tags:

sql

mysql

I have a situation where I want to set multiple variables when a condition mets.

IF(expr1, @reading:=0 and @prevdate:=@stepdate, @reading:=@reading)

as you see I want to set @reading:=0 and @prevdate:=@stepdate but this does not work.

how can I set multiple user-variables inside the true or false node?

like image 704
Pentium10 Avatar asked Jan 31 '26 02:01

Pentium10


1 Answers

Problem
The AND does short circuit evaluation.
The @reading:= 0 evaluates to 0, which is false.

0 and x is always 0, so MySQL does not bother to evaluate x.
OR suffers from the same problem: 1 OR x is alway true.
This is a way to speed things up by stopping as soon as the outcome if known.

Solution
Change it to @reading:= 0 XOR @prevdate:= @stepdate

This will solve your problem, because XOR does not suffer from short-circuit evaluation.

1 XOR x can be anything as well as 0 XOR x.

like image 198
Johan Avatar answered Feb 01 '26 18:02

Johan