轉載請註明: TheViper http://www.cnblogs.com/TheViper html
前面兩篇文章都是先把多張表的結果一併取出,而後用mybatis自動分組,實現一對多的結果集。可是,實際開發過程當中,是須要對評論分頁的,好比在mysql中使用limit.mysql
SELECT articlecomment.articlecomment_id,articlecomment.commenttime,articlecomment.commentcontent,articlecomment.id as commentuser_id ,articlereply.articlereply_id,articlereply.replytime,articlereply.replycontent,articlereply.id as replyuser_id ,u1.name AS comment_user,u2.name AS reply_user FROM articlecomment LEFT JOIN articlereply ON articlereply.comment_id=articlecomment.articlecomment_id INNER JOIN USER AS u1 ON u1.id=articlecomment.id INNER JOIN USER AS u2 ON u2.id=articlereply.id ORDER BY commenttime DESC,replytime DESC
能夠看到評論id爲1和2的評論都有3條回覆,這時對評論分頁直接用limit,好比limit 2,就取不到評論id爲1的評論,而後mybatis自動分組後就只有一條評論。sql
解決方法是外面不用limit,在where條件中,對articlecomment_id使用in子查詢,在in子查詢裏面用limit,取出指定limit的知足條件尚未外鏈接的評論的articlecomment_id。mybatis
表數據spa
SELECT articlecomment.articlecomment_id,articlecomment.commenttime,articlecomment.commentcontent,articlecomment.id AS commentuser_id ,articlereply.articlereply_id,articlereply.replytime,articlereply.replycontent,articlereply.id AS replyuser_id ,u1.name AS comment_user,u2.name AS reply_user FROM articlecomment LEFT JOIN articlereply ON articlereply.comment_id=articlecomment.articlecomment_id INNER JOIN USER AS u1 ON u1.id=articlecomment.id LEFT JOIN USER AS u2 ON u2.id=articlereply.id WHERE articlecomment.articlecomment_id IN(SELECT articlecomment1.articlecomment_id FROM articlecomment AS articlecomment1 WHERE articlecomment1.article_id=1 ORDER BY articlecomment1.articlecomment_id DESC LIMIT 2 ) ORDER BY articlecomment.articlecomment_id DESC,replytime DESC
這時會顯示錯誤,This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'。3d
很容易搜到鳥哥的這篇MySQL也真是讓人鬱悶(關於子查詢中使用limit)。在外面加一層就能夠了。code
SELECT articlecomment.articlecomment_id,articlecomment.commenttime,articlecomment.commentcontent,articlecomment.id AS commentuser_id ,articlereply.articlereply_id,articlereply.replytime,articlereply.replycontent,articlereply.id AS replyuser_id ,u1.name AS comment_user,u2.name AS reply_user FROM articlecomment LEFT JOIN articlereply ON articlereply.comment_id=articlecomment.articlecomment_id INNER JOIN USER AS u1 ON u1.id=articlecomment.id LEFT JOIN USER AS u2 ON u2.id=articlereply.id WHERE articlecomment.articlecomment_id IN(SELECT articlecomment1.articlecomment_id FROM (SELECT * FROM articlecomment AS articlecomment2 WHERE articlecomment2.article_id=1 ORDER BY articlecomment2.articlecomment_id DESC LIMIT 2) AS articlecomment1 ) ORDER BY articlecomment.articlecomment_id DESC,replytime DESC