MySQL按行排序

时间:2018-10-13 14:11:34

标签: mysql sql-order-by

我正在尝试从forum_topicsforum_replies表中提取数据以获取上次答复日期;

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

它正在记录集中获取lastreply数据,但没有使用它对记录集的行进行ORDER。

我可以看到原因,但不确定如何解决?

1 个答案:

答案 0 :(得分:1)

您应该使用相关子查询:

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