我的问题如下:
我的表格为MESSAGE
和MESSAGE_COMMENT
,
MESSAGE (id,content)
MESSAGE_COMMENT (id, message_id, content)
我需要为每封邮件选择所有邮件和 最多3条评论 ,例如:
type | id | content
M 15 "this is a message with no comments"
M 16 "this is another message with many comments"
R 16 "comment1"
R 16 "comment2"
R 16 "comment3"
M 17 "this is another message with no comments"
“id”在MESSAGE.id
为消息时为COMMENT.message_id
,在为评论时为{{1}}。
我希望我已经清楚地解释了我的问题..
答案 0 :(得分:1)
SELECT *
FROM (
SELECT m.id,
COALESCE(
(
SELECT id
FROM message_comment mc
WHERE mc.message_id = m.id
ORDER BY
mc.message_id DESC, id DESC
LIMIT 2, 1
), 0) AS mid
FROM message m
) mo
LEFT JOIN
message_comment mcd
ON mcd.message_id >= mo.id
AND mcd.message_id <= mo.id
AND mcd.id >= mid
在message_comment (message_id, id)
上创建一个索引,以便快速工作。
在我的博客中查看此文章,了解其工作原理的详细说明:
答案 1 :(得分:0)
这就是因为PHP在您的服务器(侧面)中进行了解析,并且由它生成的HTML转到客户端浏览器并进行了渲染......
答案 2 :(得分:0)
我不是工会的粉丝,但有时候他们有自己的位置...... :)。
SELECT type, id, content FROM (
SELECT 'M' AS type, id, 0 AS reply_id, content FROM MESSAGE
UNION
SELECT 'R' AS type, message_id AS id, id AS reply_id, content FROM MESSAGE_COMMENT) a
ORDER BY id, reply_id
返回
+------+----+--------------------------------------------+
| type | id | content |
+------+----+--------------------------------------------+
| M | 15 | this is a message with no comments |
| M | 16 | this is another message with many comments |
| R | 16 | comment1 |
| R | 16 | comment2 |
| R | 16 | comment3 |
| M | 17 | this is another message with no comments |
+------+----+--------------------------------------------+
注意:如果孤立的message_comments是一个问题,那么SELECT
中的第二个UNION
很容易通过INNER JOIN
重新加工到MESSAGE
表。