How to get at least 3 values โ€‹โ€‹where some of them may be empty in MySQL using the LEAST () method?

I found this question ( How to get a maximum of two values โ€‹โ€‹in MySQL? ), Looking for ways to compare a discrete set of values.

I want to get a minimum of several selected values, where some of them may be null , because they are optional, but MySQL docs says:

If any argument is NULL, the result will be NULL.

+4
source share
4 answers

Use the COALESCE() function for values โ€‹โ€‹with a null value:

 select LEAST(COALESCE(@foo, <max int>), COALESCE(@bar, <max int>)); 

if you get the maximum value of int, then both values โ€‹โ€‹were zero (if you do not have a sufficient chance of the actual value of max int as a real argument, then more logic is required)

+4
source

How about this:

 LEAST(COALESCE(col1, col2, col3), COALESCE(col2, col3, col1), COALESCE(col3, col1, col2)) 

Obviously, this does not scale to more than 3 values.

+2
source

It works, easily extends and does not depend on any values โ€‹โ€‹that are not found in the data, but are probably extremely inefficient!

 CREATE TABLE X ( Id int primary key, col1 int null, col2 int null, col3 int null ) 

Request

 SELECT id, Min(CASE c WHEN 1 THEN col1 WHEN 2 THEN col2 WHEN 3 THEN col3 END) FROM x, (SELECT 1 AS c UNION ALL SELECT 2 UNION ALL SELECT 3) t GROUP BY id 
+1
source

You need to write the code for a large number 99999.

LEAST (IFNULL (COL_1,999999),
IFNULL (COL_2,999999), IFNULL (COL_3,999999), IFNULL (COL_1,999999))

i.e. just add IFNULL and then the value or column name with a sufficiently large number.

0
source

All Articles