开发者

Detect queried field via greatest()

I'm using the mysql GREATEST() function to select the highest integer value from either column (apples or peaches).

+----+------------------+
| id | apples | peaches |
+----+------------------+
|  1 |    8   |    4   开发者_高级运维 |
|  2 |    2   |    6    |
|  3 |    3   |    9    |
|  4 |    7   |    2    |
|  5 |    4   |    4    |
+----+------------------+

Using $result = "SELECT GREATEST(apples, peaches) FROM table"; and echo $result, I get:

8
6
9
7

Next to each value, I want to echo the corresponding fruit name and a fruit icon. How can I achieve the image below via the MYSQL query?

Detect queried field via greatest()

Also, notice that equal values aren't displayed by the GREATEST() function. Is there a way to display the equal value as well?


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

or, if you don't want apples to be the default on equal and want to know when both fruits are equally represented:

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 ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜