2

My problem is the following:

My tables are MESSAGE and MESSAGE_COMMENT,

MESSAGE (id,content)

MESSAGE_COMMENT (id, message_id, content)

I need to select all messages and max 3 comments for each message, like in this example:

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" is MESSAGE.id when it's a message and COMMENT.message_id when it's a comment.

I hope I have clearly explained my problem..

4

3 回答 3

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)使其快速工作。

有关其工作原理的更详细说明,请参阅我的博客中的这篇文章:

于 2010-01-27T12:31:12.277 回答
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

于 2010-11-22T20:21:24.930 回答
0

这都是因为 PHP 在您的服务器(端)中被解析,并且由它生成的 HTML 进入客户端浏览器并被渲染......

于 2010-01-27T12:42:15.223 回答