2011-06-22 26 views
5

經過太多小時後,我無法找到答案。查找行中的最大值和回顯編號和列名

首先我的表

id | one | two | three | four | five | galname 
------------------------------------------------- 
    1 | 2 | 5 | 23 | 4 | 5 | Bob 

如何找到該行的最高值,並顯示colomun名。

three - 23 
+1

從那裏,你想獲得的信息(PHP的?) – Manuel

+3

[規格化數據(http://stackoverflow.com/questions/246701/what-i s-normalization-or-normalization-why-it-it-important) – YXD

+1

根據你想要做的事情,你的數據沒有被標準化 - 你不能在MySQL中輕鬆使用PIVOT。 – Konerak

回答

3
select id, GREATEST(one, two, three, four, five) value, 
     case GREATEST(one, two, three, four, five) 
     when one then 'one' 
     when two then 'two' 
     when three then 'three' 
     when four then 'four' 
     when five then 'five' end column_name 
from your_table   
+0

我剛剛試過這個,我不斷得到這個作爲我的結果「資源ID#3」。這是什麼意思。第3列? ive檢查mysql表和第一列的數字是最高的。林混淆 – Darren

+0

在我匆忙的混亂,我忘了感謝每一個人的答覆。非常感謝你們,真正令人驚奇的是,陌生人願意互相幫助。人類不錯 – Darren

+0

邁克爾只是想多說一句謝謝你。所有似乎都在工作。我仍然得到「Resorcue id#3」,不知道這意味着什麼,但沒關係。迴應$行似乎給了我coloum的名字。我現在可以繼續使用我的其他代碼。非常感謝。 – Darren

1

我認爲你應該做的:

SELECT CASE GREATEST(`id`,`one`, `two`, `three`, `four`, `five`) 
     WHEN `id` THEN `id` 
     WHEN `one` THEN `one` 
     WHEN `two` THEN `two` 
     WHEN `three` THEN `three` 
     WHEN `four` THEN `four` 
     WHEN `five` THEN `five` 
     ELSE 0 
     END AS maxcol, 
     GREATEST(`id`,`one`, `two`, `three`, `four`, `five`) as maxvalue 
    FROM tbl 

這只是如果你不想在這裏看看:MySQL greatest value in row? (我適應了答案從POST滿足您的需求,如果你有問題,反正是指該職位)

+0

你爲什麼要張貼他人的答案?這是從上面評論中發佈的鏈接複製的。 – Daric

+0

這正是我寫的!(我改編的答案適合你的需要意味着'如果你不想從其他答案中修改答案,我爲你做了,我想我很清楚) –

相關問題