2012-09-03 116 views
0

我有以下查询: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,这样我可以在我的下query.I使用它现在用下面的查询来这样做。

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; 

我没空,但这些变量保存最大值和列的分id,而不是这个结果set.ie 返回我最大= 52分钟= 41是的column.I需要的最小值分= 49

回答

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 
+0

嘿日Thnx的答案,你能告诉我怎么只保存在变量的最大值和最小值,而不返回resultset.I要运行的查询只一次像你above.because这里做选择统计将返回结果集,我不希望这一点。 – Mj1992

+0

@ Mj1992:嘿,我已经更新了我的答案,请现在检查 –

+0

,但是'select'会返回结果集。我希望这些变量得到填充,然后在下一个查询中使用它们以获得最终结果。将返回一个额外的行,最小值,最大值,这将导致我的问题在我的服务器端脚本。 – Mj1992

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连接语法。