2010-12-05 63 views
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";echo $result,我得到:

8 
6 
9 
7 

下一頁到每個值,我想呼應相應的水果名稱和水果圖標。如何通過MYSQL查詢實現下面的圖像?

alt text

另外,注意相等的值不被GREATEST()功能顯示。有沒有辦法顯示相等的值?

+1

你只有2列,或者這是一個簡化例? – 2010-12-05 00:21:50

+0

是的,我需要比較2列 – Noob 2010-12-05 00:26:17

回答

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