Biggest value from two or more fields

后端 未结 5 1046
不思量自难忘°
不思量自难忘° 2020-12-05 01:32

I need to get the biggest value from two fields:

SELECT MAX(field1), MAX(field2)

Now, how can I get biggest value from these two?

5条回答
  •  無奈伤痛
    2020-12-05 02:24

    Use of GREATEST/LEAST with MIN/MAX

    GREATEST/LEAST: used with the columns, when you want to find the max or min value from the various columns.

    MIN/MAX: used with the rows, when you want to find the max or min value from the various rows:

    Example table:

    SELECT GREATEST(col_a, col_b, col_c) FROM temp;
    

    SELECT MIN(GREATEST(col_a, col_b, col_c)) FROM temp; # 3 as output
    SELECT MAX(GREATEST(col_a, col_b, col_c)) FROM temp; # 9 as output
    
    
    SELECT LEAST(col_a, col_b, col_c) FROM temp;
    

    SELECT MIN(LEAST(col_a, col_b, col_c)) FROM temp; # 1 as output
    SELECT MAX(LEAST(col_a, col_b, col_c)) FROM temp; # 7 as output
    

提交回复
热议问题