DECLARE topScorer INT default 0;
SELECT id INTO topScorer FROM game_player
WHERE game_player.score = (SELECT max(score) FROM game_player)
了一個壞榜樣,但一個可以很容易地從幼稚編碼結果......它並不在我的測試工作,如果返回了多個行,我怎樣才能得到第一個返回行到變量?如何在MySQL選擇從查詢的第一行到一個程序變量
DECLARE topScorer INT default 0;
SELECT id INTO topScorer FROM game_player
WHERE game_player.score = (SELECT max(score) FROM game_player)
了一個壞榜樣,但一個可以很容易地從幼稚編碼結果......它並不在我的測試工作,如果返回了多個行,我怎樣才能得到第一個返回行到變量?如何在MySQL選擇從查詢的第一行到一個程序變量
你只需要一個分數?
SELECT id
INTO topScorer
FROM game_player
WHERE game_player.score = ( SELECT max(score) as maxScore
FROM game_player
) LIMIT 1
更新: 入佛門先生是正確的,上面的代碼已經被修正。
這個聲明是越野車,檢查它在這裏http://sqlfiddle.com/#!2/e51a0/7 –
'SELECT max(Column)FROM table'將返回一個或沒有行。 'LIMIT'這個語句是無用的 –
使用LIMIT x
可確保您僅收到查詢中的x
行。
在這種情況下,你只想得到1
行:
SELECT id
INTO topScorer
FROM game_player
WHERE game_player.score = (SELECT max(score)
FROM game_player)
LIMIT 1
作爲工作的替代,你也可以使用這個
SELECT id
INTO topScorer
FROM game_player
ORDER BY score DESC
LIMIT 1
申請限制在子查詢中只獲得1個VA泰倫從子查詢
SELECT id
INTO topScorer
FROM game_player
WHERE game_player.score = (SELECT max(score)
FROM game_player LIMIT 1);
或獲得從子查詢下面一個使用多個值:
SELECT id
INTO topScorer
FROM game_player
WHERE game_player.score in (SELECT max(score)
FROM game_player);
爲什麼你限制只能返回一行或一行的語句爲「SELECT MAX(Column)FROM Table」?並且「SELECT ... INTO ...」應該只返回1行最大值,否則會出錯 –
也許添加「LIMIT 1」 SELECT語句? ; o) –
從來沒有見過這個關鍵字,整潔 –