如何在 MySQL 中获取两个值的最大值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1565688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 14:16:02  来源:igfitidea点击:

How to get the max of two values in MySQL?

mysqlmax

提问by Mask

I tried but failed:

我试过但失败了:

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

回答by NinethSense

Use GREATEST()

使用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)

注意:当任何单个值包含 null 时,此函数始终返回 null(感谢用户 @sanghavi7)

回答by cs_alumnus

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

回答by Leonid Zakharov

You can use GREATESTfunction with not nullable fields. If one of this values (or both) can be NULL, don't use it (result can be NULL).

您可以将GREATEST函数与不可为空的字段一起使用。如果此值之一(或两者)可以为 NULL,则不要使用它(结果可以为 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).

您可以将 NULL 更改为您首选的默认值(如果两个值都是 NULL)。