I would like to get the greatest value from a set of fields but some of them can be NULL so I can't use GREATEST as it is and I have to transform NULL values to arbitrary values (-1 in this case). However in the result I still have to get NULL value if all the fields were NULL.
SELECT
CASE WHEN GREATEST(IFNULL(f1, -1), IFNULL(f2, -1)) = -1 THEN
NULL
ELSE
GREATEST(IFNULL(f1, -1), IFNULL(f2, -1))
END
My problem is, I have twice the calculation of the greatest value so I wondered if there is a way to "store" the value so that mySQL doesn't have to evaluate twice.
Or if there is a better/ more proper way to do what i want.
Thanks.
You may use NULLIF
function:
NULLIF(GREATEST(IFNULL(f1, -1), IFNULL(f2, -1)), -1)
It would return NULL
if they equal, or the value of the first argument otherwise.
References:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.