2

我正在使用 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";and echo $result,我得到:

8
6
9
7

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

替代文字

另外,请注意,函数不显示相等的值GREATEST()。有没有办法显示相等的值?

4

1 回答 1

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 ...
于 2010-12-05T00:20:15.970 回答