来自两个或多个字段的最大值

时间:2010-04-11 01:26:00

标签: mysql

我需要从两个领域获得最大价值:

SELECT MAX(field1), MAX(field2)

现在,我怎样才能从这两个中获得最大价值?

5 个答案:

答案 0 :(得分:140)

您可能想要使用GREATEST()功能:

SELECT GREATEST(field1, field2);

如果要从所有行获得绝对最大值,则可能需要使用以下内容:

SELECT GREATEST(MAX(field1), MAX(field2));

示例1:

SELECT GREATEST(1, 2);
+----------------+
| GREATEST(1, 2) |
+----------------+
|              2 |
+----------------+
1 row in set (0.00 sec)

示例2:

CREATE TABLE a (a int, b int);

INSERT INTO a VALUES (1, 1);
INSERT INTO a VALUES (2, 1);
INSERT INTO a VALUES (3, 1);
INSERT INTO a VALUES (1, 2);
INSERT INTO a VALUES (1, 4);

SELECT GREATEST(MAX(a), MAX(b)) FROM a;
+--------------------------+
| GREATEST(MAX(a), MAX(b)) |
+--------------------------+
|                        4 |
+--------------------------+
1 row in set (0.02 sec)

答案 1 :(得分:27)

如果您为每一行选择GREATEST()

SELECT GREATEST(field1, field2)

如果其中一个字段为NULL,它将返回 NULL 。您可以使用IFNULL来解决这个问题

SELECT GREATEST(IFNULL(field1, 0), IFNULL(field2, 0))

答案 2 :(得分:6)

mysql> SELECT GREATEST(2,0);
        -> 2

所以,试试:

mysql> SELECT GREATEST(MAX(field1), MAX(field2));

答案 3 :(得分:0)

SELECT max( CASE
                WHEN field1 > field2 THEN field1
                ELSE field2
            END ) as biggestvalue 
FROM YourTable;

答案 4 :(得分:0)

将GREATEST / LEAST与MIN / MAX结合使用

GREATEST / LEAST :当您要从各个列中查找最大值或最小值时,可与这些列一起使用。

MIN / MAX :与行一起使用,当您要从各个行中查找最大值或最小值时:

示例表:

enter image description here

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

enter image description here

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;

enter image description here

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