Cómo obtener el máximo de dos valores en MySQL?


Lo intenté pero fallé:

mysql> select max(1,0);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual 
that corresponds to your MySQL server version for the right syntax to use 
near '0)' at line 1
 237
Author: Taryn, 2009-10-14

3 answers

Uso EL MÁS GRANDE()

Ej:

SELECT GREATEST(2,1);
 433
Author: NinethSense,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-11 21:05:31

Para obtener el valor máximo de una columna a través de un conjunto de filas:

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

Para obtener el valor máximo de un conjunto de columnas, literales o variables para cada fila:

SELECT GREATEST(column1, 1, 0, @val) FROM table; -- expect many results
 21
Author: cs_alumnus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-13 18:07:18

Puede usar la función GREATEST con campos que no se pueden anular. Si uno de estos valores (o ambos) puede ser NULO, no lo use (el resultado puede ser NULO).

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

Puede cambiar NULL a su valor predeterminado preferido (si ambos valores son NULL).

 4
Author: Leonid Zakharov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-09 00:16:12