MySQL 在具有多个连接的组内排序
我正在尝试使用下表: 用户(ID、姓名) 主题(id、名称、slug) 帖子(id、标题、内容、topicid、authorid、日期时间、slug) 回复(id、authorid、threadid、内容、日期时间)
我想创建一个按最新回复(如果没有回复则按发布日期)排序的帖子列表。每个列表应该包含:帖子标题、回复数、发帖日期、最近回复日期、作者姓名、最后回复者姓名等。
我可以获得除最新回复的日期和作者。日期可以通过 MAX(replies.datetime) 完成,但我不知道如何获取最新的作者。
我的最后一次尝试是尝试使用排除连接:
select posts.id, posts.title, posts.authorid, posts.topicid, posts.content, posts.datetime, count(replies.id) as replies, r2.datetime, replies.datetime, GREATEST(posts.datetime, coalesce(max(replies.datetime), posts.datetime)) as latesttime, users.name as author, commenters.name as commenter, r2.id
from posts
left join replies on replies.threadid = posts.id
left join users on users.id = posts.authorid
left join users commenters on commenters.id = replies.authorid
left join replies as r2 on replies.id = r2.id and replies.datetime < r2.datetime
where r2.id is null
group by posts.id
order by latesttime DESC, replies.datetime DESC
limit 20;
不幸的是,这仍然无法检索最新的评论作者。有什么想法吗?
I am attempting to work with the following tables:
users (id, name)
topics (id, name, slug)
posts (id, title, content, topicid, authorid, datetime, slug)
replies (id, authorid, threadid, content, datetime)
I want to create a list of posts ordered by latest reply (or the post date if there are no replies). Each listing should contain: the post title, the number of replies, the date of the post, the date of the latest reply, the name of the author, the name of the person who last replied, etc.
I can get everything except the date and author of the latest reply. The date can be done via MAX(replies.datetime), but I'm not sure how to get the latest author.
My last attempt was trying to use an exclusion join:
select posts.id, posts.title, posts.authorid, posts.topicid, posts.content, posts.datetime, count(replies.id) as replies, r2.datetime, replies.datetime, GREATEST(posts.datetime, coalesce(max(replies.datetime), posts.datetime)) as latesttime, users.name as author, commenters.name as commenter, r2.id
from posts
left join replies on replies.threadid = posts.id
left join users on users.id = posts.authorid
left join users commenters on commenters.id = replies.authorid
left join replies as r2 on replies.id = r2.id and replies.datetime < r2.datetime
where r2.id is null
group by posts.id
order by latesttime DESC, replies.datetime DESC
limit 20;
Unfortunately, this still won't retrieve the latest comment author. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须首先从给定线程的最大 ID 的最内部查询开始,并将其回复 ID 加入到原始回复中以获得一个实例...从中,您可以获得回复作者的信息。然后,根据需要获取原始发布信息。
You have to first start with an inner most query on the max ID for a given thread and what it's REPLY ID was joined to the original replies to get ONE instance... From that, you can get the reply author's information. THEN, get original posting information as needed.
你能测试一下吗?
uld you test it?