mysql查询没有在变量中保存正确的结果

时间:2012-09-03 12:23:46

标签: mysql

我有以下问题:

select wall.postid from wall,posts where  
wall.postid = posts.postid and posts.userid=puserid
order by wall.postid desc LIMIT 4 OFFSET 0;

以下列方式返回结果。

  wall.postid
-----------------
      52
      51
      50
      49

现在我想在变量中保存最大值,即52和最小值,即49,这样我就可以在下一个查询中使用它。我使用以下查询来执行此操作。

select @upper:=max(wall.postid),@lower:=min(wall.postid) from wall,posts where  
wall.postid = posts.postid and posts.userid=puserid
order by wall.postid desc LIMIT 4 OFFSET 0;

我已经这些变量保存了列的最大值和最小值,而不是这个结果集.i.e 它返回我max = 52和min = 41这是该列的最小值。我需要min = 49。

2 个答案:

答案 0 :(得分:2)

您需要在聚合之前执行限制以获得所需的结果

 select
     @upper = max(postID),
     @lower = min(postID)
 from
 (
      select wall.postid from wall 
          inner join posts on wall.postid = posts.postid 
      where   
      posts.userid=puserid 
      order by wall.postid desc LIMIT 4 OFFSET 0
 ) as v

还要注意改进的ANSI-92连接语法。

答案 1 :(得分:0)

select @upper:=max(`postid`), @lower:=MIN(`postid`) 
from
(
select wall.postid from wall,posts where  
wall.postid = posts.postid and posts.userid=puserid
order by wall.postid desc LIMIT 4 OFFSET 0)m