开发者

Ordering by posts in another table

I have created a feature where users can start new topics (similar to forums). At the moment on a page, the query for the topics are as follows:

$q = "SELECT ".TBL_COMMUNITYTHREADS.".title, ".TBL_COMMUNITYTHREADS.".id, 
    ".TBL_COMMUNITYTHREADS.".date, ".TBL_COMMUNITYTHREADS.".author, ".TBL_USERS.".username FROM ".TBL_COMMUNITYTHREADS." 
        INNER JOIN ".TBL_USERS." ON ".TBL_COMMUNITYTHREADS.".author = ".TBL_USERS.".id
        WHERE type = '$type'
        ORDER BY date DESC LIMIT $offset, $rowsper开发者_StackOverflow社区page ";

The tables are constants and the offset and rowsperpage are variables passed in to limit how many posts are on a page.

At the moment though, all the topics are ordered by the date. I want them to be ordered by the latest response. Similarly to forums, when the reponse inside the topic is newest, that topic will go to the top.

The topics are stored in tbl_communitythreads and the replies in tbl_communityreplies.

How can I ordered them by the latest repsonse.

They are linked by the threadid in tbl_communityreplies. Also in that one is the date column.

Thankyou for reading, I just cant think of how to do this.


This:

SELECT  c.title, c.id, c.date, c.author, u.username,
        (
        SELECT  MAX(reply_date)
        FROM    tbl_communityreplies cr
        WHERE   cr.thread = c.id
        ) AS last_reply
FROM    TBL_COMMUNITYTHREADS c
JOIN    TBL_USERS u
ON      u.id = c.author
ORDER BY
        last_reply DESC, c.id DESC
LIMIT   $offset, $rowsperpage

or this:

SELECT  c.title, c.id, c.date, c.author, u.username
FROM    (
        SELECT  cr.thread, cr.reply_date, cr.id
        FROM    tbl_communityreplies cr
        WHERE   (cr.last_reply, cr.id) = 
                (
                SELECT  last_reply, id
                FROM    tbl_communityreplies cri
                WHERE   cri.thread = cr.thread
                ORDER BY
                        thread DESC, last_reply DESC, id DESC
                )
        ORDER BY
                last_reply DESC, id DESC
        LIMIT   $offset, $rowsperpage
        ) q
JOIN    TBL_COMMUNITYTHREADS c
ON      c.id = q.thread
JOIN    TBL_USERS u
ON      u.id = c.author
ORDER BY
        q.reply_date DESC, q.id DESC

The former query is more efficient for large values of $offset, or if you have few threads with lots of replies.

Issue the following commands:

CREATE INDEX ix_communitythreads_replydate_id ON TBL_COMMUNITYTHREADS (reply_date, id)
CREATE INDEX ix_communitythreads_thread_replydate_id ON TBL_COMMUNITYTHREADS (thread, reply_date, id)

for this to work fast.


by join with another table , then you can order by column from this table.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜