我有一个查询以这种降序返回结果。获取结果集中每个id的`n`行MYSQL
comment postid name userid tempid
-----------------------------------------------------
c1 199 User1 123321 1
c2 199 User1 123321 2
c3 199 User1 123321 3
c4 199 User1 123321 4
c5 199 User1 123321 5
c6 199 User1 123321 6
c7 198 User1 123321 7
c8 198 User1 123321 8
c9 198 User1 123321 9
c10 197 User1 123321 10
c11 197 User1 123321 11
c12 197 User1 123321 12
c13 197 User1 123321 13
c14 197 User1 123321 13
c15 197 User1 123321 13
c16 197 User1 123321 13
现在我想选择前5个记录每个postid
.The dersired结果应该是
comment postid name userid tempid
-----------------------------------------------------
c1 199 User1 123321 1
c2 199 User1 123321 2
c3 199 User1 123321 3
c4 199 User1 123321 4
c5 199 User1 123321 5
c7 198 User1 123321 7
c8 198 User1 123321 8
c9 198 User1 123321 9
c10 197 User1 123321 10
c11 197 User1 123321 11
c12 197 User1 123321 12
c13 197 User1 123321 13
c14 197 User1 123321 13
这里是我的查询。
DECLARE rangee INT;
DECLARE uid BIGINT;
SET @rangee = plimitRange * 10;
SET @uid = puserid;
PREPARE STMT FROM
'
SELECT comments.comment,comments.postid,user.name,comments.userid,comments.tempid
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 = ?
ORDER BY comments.postid DESC,comments.tempid DESC;
';
EXECUTE STMT USING @uid,@rangee,@uid,@rangee,@uid;
DEALLOCATE PREPARE STMT;
我该如何做到这一点?
我会想象得到的意见表从子查询,上面有一个极限,而不是直接加入会起作用。可能相关:http://stackoverflow.com/q/2856397/438971 – Orbling
thnx的答复,但你可以帮助我在查询中指定它? – Mj1992
你看过评论中的答案链接吗?在MySQL中的高级采样,这有点令人困惑:http://explainextended.com/2009/03/06/advanced-row-sampling/ – Orbling