提取最近发布的 MySQL 主题摘要
我有一个非常基本的论坛系统。三个主表(主题、评论和用户)拥有您能想象到的所有常用字段,例如相互之间的自动增量主键和外键,所以我认为我不需要详细说明这
一切我想做的是获取最近发布的主题列表。列表视图应显示主题标题、初始评论/帖子的正文以及作者姓名,但列表应按最近发布的主题排序。
除了最基本的查询之外,我不太擅长 MySQL。显然,我可以将其分解为多个查询,但为了提高性能,我希望将其放在一个查询中。
这是我首先想到的,但它根据第一篇文章的时间对主题进行排序。
SELECT topic.id as topic_id, topic.title as topic_title, topic.datePosted as datePosted, topic.views as views, topic.numComments as numComments,
comment.ID as commentID, comment.body as body,
user.ID as userID, user.firstName, user.lastName, user.title as user_title, user.city, user.state, user.thumbnail
FROM comment INNER JOIN topic ON comment.topicID = topic.id
INNER JOIN user ON comment.userID = user.id
WHERE comment.id
IN (
SELECT min( comment.id )
FROM COMMENT INNER JOIN topic ON comment.topicID = topic.id
GROUP BY topic.id
)
ORDER BY commentID desc';
I have a pretty basic forum system. The three main tables, Topic, Comment, and User have all the usual fields you would imagine such as auto-increment primary keys and foreign keys to each other, so I don't think I need to lay that all out in great detail
What I'm trying to do is get a list of the most recently posted in topics. The list view should show the topic title, the body of the initial comment/post, and the author's name, but the list should be ordered with the topics that were most recently posted in first.
I'm not very good at MySQL beyond the most basic of queries. I could obviously break it up into multiple queries, but I want it in one query for performance.
Here's what I came up with first, but it orders the topics according to the time of the first post.
SELECT topic.id as topic_id, topic.title as topic_title, topic.datePosted as datePosted, topic.views as views, topic.numComments as numComments,
comment.ID as commentID, comment.body as body,
user.ID as userID, user.firstName, user.lastName, user.title as user_title, user.city, user.state, user.thumbnail
FROM comment INNER JOIN topic ON comment.topicID = topic.id
INNER JOIN user ON comment.userID = user.id
WHERE comment.id
IN (
SELECT min( comment.id )
FROM COMMENT INNER JOIN topic ON comment.topicID = topic.id
GROUP BY topic.id
)
ORDER BY commentID desc';
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,这是我对您所要求的内容的第一次攻击,即每个主题中最近发布的评论的列表。如果这不是您正在寻找的内容,请告诉我:
如果我误解了您正在寻找的内容,您可以发布您想要的结果的示例吗?
Okay, here's my first whack at what I think you're asking for, a list of most recently posted comments in each topic. Let me know if this isn't what you're looking for:
If I've misunderstood what you're looking for, can you post an example of your desired results?