我仍然没有按照我想要的方式找到正确的方法。我试图实现的是一个评论帖子部分,它将显示帖子的最后一个回复
我的表结构是这样的
table post --------------------- post_id | comment | post_user | post_date post_reply --------------------- reply_id | parent_id | reply_user | reply_date
实际上我能够获取所有帖子和所有回复,但我面临的问题是我想限制我获取的帖子数量和我获取的每个帖子的回复数量,我也想如果没有回复则显示帖子,结果应该如下所示
result ---------------------------------------------- post 1 reply post 1 reply post 1 post 2 post 3 reply post 3 reply post 3
当然我想显示这个,直到我达到10个帖子并且2个回复最大附加到每个帖子当然可能的查询较少。实际上我正在使用一段时间查询每个帖子的最后2个回复,但是每次使用11个查询也许你们知道更好的方法来做更少的查询
答案 0 :(得分:0)
我假设您的ID列是INT类型。如果没有,您可能必须使用变量来计算每篇帖子的回复,描述为here。
所以试试这个
SELECT 'POST' AS type, p1.post_id, p1.comment, p1.post_user, p1.post_date, '-' AS reply_id
FROM post p1
LIMIT 10
UNION
SELECT 'REPLY' AS type, pr.parent_id AS post_id,
'-' AS comment, pr.reply_user AS post_user, pr.reply_date AS post_date, pr.reply_id
FROM post_reply pr
JOIN (
SELECT p2.post_id
FROM post p2
LIMIT 10
) AS tmpPost ON pr.parent_id = tmpPost.post_id
JOIN (
SELECT pr.reply_id, COUNT(*) AS row_number
FROM post_reply pr
JOIN post_reply pr2 ON pr.parent_id = pr2.parent_id AND pr.reply_id >= pr2.reply_id
GROUP BY pr.reply_id
) AS tmpPostRN ON tmpPostRN.reply_id = pr.reply_id
WHERE tmpPostRN.row_number <= 2
ORDER BY post_id ASC, type ASC, reply_id ASC
结果将类似于
+-------+---------+-----------+-----------------+------------+----------+
| type | post_id | comment | post_user | post_date | reply_id |
+-------+---------+-----------+-----------------+------------+----------+
| POST | 1 | comment1 | user1 | 0000-00-00 | -1 |
| REPLY | 1 | - | post 1 reply1 | 0000-00-00 | 1 |
| REPLY | 1 | - | post 1 reply 2 | 0000-00-00 | 2 |
| POST | 2 | comment2 | user2 | 0000-00-00 | -1 |
| POST | 3 | comment3 | user3 | 0000-00-00 | -1 |
| REPLY | 3 | - | post 3 reply 1 | 0000-00-00 | 3 |
| REPLY | 3 | - | post 3 reply 2 | 0000-00-00 | 4 |
| POST | 4 | comment4 | user 4 | 0000-00-00 | -1 |
| POST | 5 | comment5 | user 5 | 0000-00-00 | -1 |
| POST | 6 | comment6 | user6 | 0000-00-00 | -1 |
| POST | 7 | comment7 | user7 | 0000-00-00 | -1 |
| POST | 8 | comment8 | user8 | 0000-00-00 | -1 |
| POST | 9 | comment9 | user9 | 0000-00-00 | -1 |
| POST | 10 | comment10 | user10 | 0000-00-00 | -1 |
| REPLY | 10 | - | post 10 reply 1 | 0000-00-00 | 5 |
| REPLY | 10 | - | post 10 reply 2 | 0000-00-00 | 6 |
+-------+---------+-----------+-----------------+------------+----------+
而不是第二个查询中的'-' AS comment
,您可以在post_reply表中插入注释列(假设您有一个)。您还可以将帖子的reply_id设置为您选择的默认值(而不是-1)。