通过最大()检测查询字段

时间:2010-12-05 00:11:45

标签: php mysql sql database-table

我正在使用mysql GREATEST()函数从任一列(苹果或桃子)中选择最高整数值。

+----+------------------+
| id | apples | peaches |
+----+------------------+
|  1 |    8   |    4    |
|  2 |    2   |    6    |
|  3 |    3   |    9    |
|  4 |    7   |    2    |
|  5 |    4   |    4    |
+----+------------------+

使用$result = "SELECT GREATEST(apples, peaches) FROM table";echo $result,我得到:

8
6
9
7

在每个值旁边,我想回显相应的水果名称和水果图标。如何通过MYSQL查询实现下图?

alt text

另请注意,GREATEST()功能不会显示相等的值。有没有办法显示同等价值?

1 个答案:

答案 0 :(得分:4)

SELECT 
IF(apples >= peaches, apples, peaches) AS quantity,
IF(apples >= peaches, 'apples', 'peaches') AS fruit
FROM ...

或者,如果您不希望苹果在默认情况下是平等的,并想知道两种水果的平均表示时间:

SELECT 
IF(apples >= peaches, apples, peaches) AS quantity,
CASE WHEN apples > peaches THEN 'apples' WHEN peaches > apples THEN 'apples' ELSE 'both' END AS fruit
FROM ...