用于在一张表中显示和排序消息及其回复的 SQL

发布于 2024-10-26 00:39:02 字数 402 浏览 3 评论 0原文

我为正在开发的 CMS 编写了一个简单的消息系统,但很难找到获取所有消息及其按最新顺序排序的回复(消息或回复)的最佳方法。

我有一个名为“messages”的表,其中包含以下字段: *id, active[1,0], subject, message, datetime, user_from, user_to,reply_id*

这一切都很简单,*reply_id* 对于主级消息来说是空的,并且包含父 id回复。我不知道如何编写 SQL 来根据他们自己和他们的回复以 datetime DESC 顺序获取所有主要级别的消息。我确信这是通过某种 UNION 完成的,但我缺乏 SQL 技能。如果相同的 SELECT 可以给出每个主级别消息中的回复计数,那就太棒了!

任何帮助将不胜感激!

I have written a simple messaging system for a CMS I am developing and am having a hard time finding the best way to grab all the messages and their replies ordered by the newest (message or reply).

I have a table called "messages" that has the fields:
*id, active[1,0], subject, message, datetime, user_from, user_to, reply_id*

It's all straight forward and the *reply_id* is empty for main level messages and contains the parent id for replies. I am at a loss for how to write the SQL to grab all the main level messages in datetime DESC order based on themselves AND their replies. I'm sure it's done with a UNION of some sort but my SQL skills are lacking. And if the same SELECT can give a count of the replies within each main level message that would be amazing!

Any help would be greatly appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

溺深海 2024-11-02 00:39:02

已经很晚了,我很累,但我想你可以尝试这样的事情:

SELECT main.*, COUNT(reply.id) AS cnt_replies, MAX(reply.datetime) AS max_datetime
FROM posts AS main
LEFT JOIN posts AS reply
    ON main.id = reply.reply_id
GROUP BY main.id
HAVING main.reply_id IS NULL
ORDER BY max_datetime DESC

编辑:固定查询
EDIT2:现在包含没有任何回复的消息

It's late and I'm tired but I think you could try something like that:

SELECT main.*, COUNT(reply.id) AS cnt_replies, MAX(reply.datetime) AS max_datetime
FROM posts AS main
LEFT JOIN posts AS reply
    ON main.id = reply.reply_id
GROUP BY main.id
HAVING main.reply_id IS NULL
ORDER BY max_datetime DESC

EDIT: fixed query
EDIT2: now includes messages without any replies

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文