2012-09-05 22 views
0

我有以下程序它說can't reopen table爲什麼它給這個error.Here是查詢:不能重新打開表的MySQL

DECLARE rangee INT; 
DECLARE uid BIGINT; 

SET @rangee = plimitRange * 10; 
SET @uid = puserid; 

DROP TEMPORARY TABLE IF EXISTS Rangee; 
CREATE TEMPORARY TABLE Rangee(max BIGINT,min BIGINT); 

PREPARE STMT FROM 
'INSERT INTO Rangee 
select max(postid),MIN(postid) from 
(
select wall.postid from wall,posts where 
wall.postid = posts.postid and posts.userid=? 
order by wall.postid desc LIMIT 10 OFFSET ? 
)m; 
'; 

EXECUTE STMT USING @uid,@rangee; 
DEALLOCATE PREPARE STMT; 


select comments.comment,comments.postid,user.name,comments.userid 
from user,posts,comments where 
posts.postID = comments.postid and 
comments.postid<=(select max from Rangee) and 
comments.postid>=(select min from Rangee) and posts.userid = puserid and 
user.userid=comments.userid order by comments.postid desc; 

在這裏,我從插入值minmax id's在臨時表另一個表,這樣我就可以使用這些值在最終查詢中檢索我的數據。但在最後一個查詢中,我指定範圍,即包含(select max from Rangee)(select min from Rangee)的行正在給出此錯誤。如何解決該錯誤。值最小和最大的回報很好。

回答

0
<UPDATE> 

然後忘掉整個過程,這樣做在一個查詢:

select comments.comment,comments.postid,user.name,comments.userid 
from 
user 
INNER JOIN comments ON user.userid=comments.userid 
INNER JOIN posts ON posts.postID = comments.postid 
WHERE 
comments.postid <= 
(select MAX(postid) from 
    (
    select wall.postid from wall,posts where 
    wall.postid = posts.postid and posts.userid=? 
    order by wall.postid desc LIMIT 10 OFFSET ? 
    )sq1 
) 

and 
comments.postid >= 
(select MIN(postid) from 
    (
    select wall.postid from wall,posts where 
    wall.postid = posts.postid and posts.userid=? 
    order by wall.postid desc LIMIT 10 OFFSET ? 
    )sq2 
) 
and 
posts.userid = puserid 
order by comments.postid desc; 

就是這樣。

</UPDATE> 

老答案...

DECLARE rangee INT; 
DECLARE uid BIGINT; 

SET @rangee = plimitRange * 10; 
SET @uid = puserid; 

PREPARE STMT FROM 
'select @max_postid := MAX(postid), @min_postid := MIN(postid) from 
(
select wall.postid from wall,posts where 
wall.postid = posts.postid and posts.userid=? 
order by wall.postid desc LIMIT 10 OFFSET ? 
)m; 
'; 

EXECUTE STMT USING @uid,@rangee; 
DEALLOCATE PREPARE STMT; 


select comments.comment,comments.postid,user.name,comments.userid 
from user,posts,comments where 
posts.postID = comments.postid and 
comments.postid<[email protected]_postid and 
comments.postid>[email protected]_postid and posts.userid = puserid and 
user.userid=comments.userid order by comments.postid desc; 

你並不需要一個臨時表在所有。此外,如果執行comments.postid <= (select max from Rangee)會很糟糕,因爲這可能會返回多行。你至少應該使用comments.postid <= (select MAX(max) from Rangee)

也讀this

+0

thnx爲答案@tombom我已經試過這個,它工作正常,但在這個問題是,它會返回我'2結果',我不想要。我只想要最後一個查詢的結果。prepare語句中的select將返回結果,然後我的最終查詢將返回另一個結果。 – Mj1992

+0

我明白了。更新了我的答案。別擔心,因爲查詢看起來很複雜。它不一定會運行得更慢或什麼。 MySQL的優化器做得非常好,可以檢測子查詢何時重複(只有很小的差異)。 – fancyPants

+0

它給出了以下錯誤「每個派生表必須有它自己的別名」。 – Mj1992

相關問題