简体   繁体   中英

MySQL ordering rows by

I'm trying to pull data from my forum_topics and forum_replies tables to get the last reply date;

SELECT 
    (SELECT date FROM forum_replies WHERE topic=5 AND date < NOW()
    ORDER BY id DESC LIMIT 1) as lastreply, 
    ft.* FROM forum_topics ft
    ORDER by lastreply DESC LIMIT 5

It's getting the lastreply data in the recordset, but not using it to ORDER the rows of the recordset.

I can see why, but not sure how to fix it?

You should use correlated subquery:

SELECT 
    (SELECT r.date FROM forum_replies r WHERE ft.topic = r.topic
    ORDER BY r.id DESC LIMIT 1) as lastreply, 
    ft.* 
FROM forum_topics ft
ORDER by lastreply DESC LIMIT 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM