按联合表数据排序

时间:2016-05-07 11:43:36

标签: mysql

这是我的表格:

主题

topic_id    name
1           "Help!"
2           "Hey!"
3           "What?"

帖子

post_id    topic    date        content
1          2        2016-05-01  "Hey there!"
2          1        2016-05-04  "How to use WIFI?"
3          1        2016-05-05  "I dont know"
4          1        2016-05-02  "What is WIFI?"
5          3        2016-05-06  "What what?"
6          2        2016-05-02  "Hello"

我有这段代码

SELECT * from topics
LEFT JOIN posts
ON posts.topic = topics.topic_id

我想仅将帖子加入最后(最近)记录,并按 posts.date 对来自主题的记录进行排序, 但我不知道怎么做。

预期结果:

topic_id    post_id   date          ...
3           5         2016-05-06    ...
1           3         2016-05-05    ...
2           6         2016-05-02    ...

2 个答案:

答案 0 :(得分:2)

请尝试此查询

SELECT * from topics LEFT JOIN posts ON posts.topic = topics.topic_id
Left join (Select posts.topics, Max(posts.date) as Date From posts Group by posts.topics) as postgroup
on posts.date = postgroup.date and posts.topic = postgroup.topics;

答案 1 :(得分:1)

我假设post_id定义了最后一条记录。您可以通过各种方式执行此操作。这是一个使用WHERE和相关子查询的方法:

SELECT * 
FROM topics t LEFT JOIN
     posts p
     ON p.topic = t.topic_id
WHERE p.post_id = (SELECT MAX(p2.post_id) FROM posts p2 WHERE p2.topic = p.topic)
ORDER BY p.post_date DESC;