我正在使用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查询实现下图?
另请注意,GREATEST()
功能不会显示相等的值。有没有办法显示同等价值?
答案 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 ...