1
DECLARE topScorer INT default 0;

SELECT id INTO topScorer FROM game_player
WHERE game_player.score = (SELECT max(score) FROM game_player)

一个不好的例子,但很容易由幼稚的编码产生......如果返回多行,它在我的测试中不起作用,我怎样才能将第一个返回的行放入变量中?

4

4 回答 4

2

你只需要一个分数吗?

SELECT id 
  INTO topScorer 
  FROM game_player
 WHERE game_player.score = (   SELECT max(score) as maxScore 
                                 FROM game_player 
                                 ) LIMIT 1

更新:Rufo 爵士是对的,上面的代码现已更正。

于 2013-01-15T10:57:46.840 回答
1

用于LIMIT x确保您只接收x来自查询的行。

在这种情况下,您只想获取1行:

SELECT id 
  INTO topScorer 
  FROM game_player
 WHERE game_player.score = ( SELECT max(score) 
                               FROM game_player )
 LIMIT 1

SQL 小提琴演示

作为一种可行的选择,您也可以使用它

  SELECT id 
    INTO topScorer 
    FROM game_player
ORDER BY score DESC
   LIMIT 1

SQL 小提琴演示

于 2013-01-15T12:59:36.253 回答
1

在子查询中应用限制以仅从子查询中获取 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
 WHERE game_player.score in ( SELECT max(score) 
                               FROM game_player );
于 2013-01-15T13:39:59.050 回答
0

1)在SP中声明变量:

declare @CourseID int 
set @CourseID = 0

2)我们首先需要两个查询来为变量分配 ID,而内部查询则只选择前 1 个记录表单表。在第一个查询的 where 子句中,我们将 ID 与内部查询的结果进行比较:

SELECT @CourseID = ID FROM Course ID = ( Select Top 1 ID from Course ) 

3)现在检查变量值:

 if(@CourseID > 0 )
    Begin
           //This mean ID of first row is assigned to CourseID
    End
    Else 
    Begin
      //Can't found any record.
    End
于 2018-09-28T06:03:58.040 回答