You do not need to join the same table several times, in MySQL there is a function to obtain the highest value among several values, it is the function GREATEST
, which according to the documentation:
With two or more arguments, returns the largest (maximum-valued)
argument.
Returns the largest argument among several arguments.
For example, here you get the largest for each row:
SET TIENDA_MAYOR = GREATEST(STOCK_TIENDA1, STOCK_TIENDA2, STOCK_TIENDA3)
FROM TB1 WHERE ...
If you want the largest of the entire table between those three columns:
SET TIENDA_MAYOR = MAX(GREATEST(STOCK_TIENDA1, STOCK_TIENDA2, STOCK_TIENDA3))
FROM TB1 ...
Very important: It's not NULL safe
Now, there is an important warning in the documentation that it is necessary not to ignore:
GREATEST()
returns NULL
if any argument is NULL
.
GREATEST()
returns NULL
if any argument is NULL
.
It's a very common problem in MySQL, but it's very easy to make our query NULL safe by using COALESCE
:
SET TIENDA_MAYOR = GREATEST(
COALESCE(STOCK_TIENDA1,0),
COALESCE(STOCK_TIENDA2,0),
COALESCE(STOCK_TIENDA3,0)
)
FROM TB1 WHERE ...
Or by using IFNULL
:
SET TIENDA_MAYOR = GREATEST(
IFNULL(STOCK_TIENDA1,0),
IFNULL(STOCK_TIENDA2,0),
IFNULL(STOCK_TIENDA3,0)
)
FROM TB1 WHERE ...
What COALESCE
or IFNULL
will do is convert the value to 0
when it is NULL
, thus preventing the result from being nulified when a single value appears NULL
. In short, MySQL is not democratic in many functions :)