How to get the max of two values in MySQL?

前端 未结 3 1855
时光说笑
时光说笑 2020-11-30 22:30

I tried but failed:

mysql> select max(1,0);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual 
that correspo         


        
相关标签:
3条回答
  • You can use GREATEST function with not nullable fields. If one of this values (or both) can be NULL, don't use it (result can be NULL).

    select 
        if(
            fieldA is NULL, 
            if(fieldB is NULL, NULL, fieldB), /* second NULL is default value */
            if(fieldB is NULL, field A, GREATEST(fieldA, fieldB))
        ) as maxValue
    

    You can change NULL to your preferred default value (if both values is NULL).

    0 讨论(0)
  • 2020-11-30 23:08

    Use GREATEST()

    E.g.:

    SELECT GREATEST(2,1);
    

    Note: Whenever if any single value contains null at that time this function always returns null (Thanks to user @sanghavi7)

    0 讨论(0)
  • 2020-11-30 23:18

    To get the maximum value of a column across a set of rows:

    SELECT MAX(column1) FROM table; -- expect one result
    

    To get the maximum value of a set of columns, literals, or variables for each row:

    SELECT GREATEST(column1, 1, 0, @val) FROM table; -- expect many results
    
    0 讨论(0)
提交回复
热议问题