获取每个记录组的最后一条记录

3

我不知道如何编写SQL语法以获取最后一条记录(根据最近的帖子并且没有回复)。

我的表格:

+-------------------+-----------------------+------+-----+---------+----------------+
| Field             | Type                  | Null | Key | Default | Extra          |
+-------------------+-----------------------+------+-----+---------+----------------+
| notification_id   | mediumint(8) unsigned | NO   | PRI | NULL    | auto_increment |
| user_id           | mediumint(8) unsigned | NO   |     | NULL    |                |
| notification_msg  | text                  | NO   |     | NULL    |                |
| notification_date | int(11) unsigned      | NO   |     | NULL    |                |
| private_message   | tinyint(1) unsigned   | NO   |     | 0       |                |
| has_replied       | tinyint(1) unsigned   | NO   |     | 0       |                |
| reply_id          | mediumint(8) unsigned | NO   |     | 0       |                |
+-------------------+-----------------------+------+-----+---------+----------------+

基本上,对于每个线程通知,它应该获取每个通知记录的最后一条记录,并检查has_replied是否为0,如果为0,则应将其返回,以便PHP可以读取是否存在未回复的通知。因此,它应该像这样返回(伪代码):

+--------------+-----+-----+
| username     | 1   | 4   |
| username2    | 0   | 2   |
+--------------+-----+-----+

第二列代表最后一篇帖子是否已回复。

我的当前SQL语法(可以工作但无法获取最后一条记录及其回复情况):

SELECT n.*,
       m.user_id,
       m.username
FROM notifications n
INNER JOIN members m ON n.user_id = m.user_id
WHERE private_message = 1
AND reply_id = 0
ORDER BY has_replied ASC,
         notification_date DESC

2
+1. 我喜欢表格格式 :) - Oscar Mederos
伪输出中的第三列是什么? - James C
2个回答

1
Select m.user_id, m.username
    , N...
From members As M
    Join    (
            Select user_id, Max( notification_id ) As notification_id
            From notifications 
            Group By user_id
            ) As UserLastNotification
        On UserLastNotification.user_id = m.user_id
    Join notifications As N
        On N.notification_id = UserLastNotification.notification_id
Where N.private_message = 1
    And N.reply_id = 0
Order By N.has_replied, N.notification_date Desc

请注意,这将过滤每个用户的最后一条通知是私人消息并且回复 ID 为零。

假设你认为LEFT OUTER JOIN或者INNER JOINJOIN更好?如果我错了请纠正我。 - MacMac
@lolwut - JoinInner Join 的简写。同样,Left JoinLeft Outer Join 的简写。然而,使用 Left Join 还是 Inner Join 取决于你想要实现什么目标。如果你想要所有成员无论是否有通知,那么我需要将 UserLastNotification 中的条件从 Where 子句移动到 On 子句中。 - Thomas
抱歉打扰您了。但是能否稍微修改一下SQL语法,以返回每个线程通知中最后一篇帖子的“user_level”。只要不太麻烦就行。 “user_level”来自成员表。 - MacMac
@lolwut - 你为什么不能将它直接添加到Select子句中,因为它来自于members表呢? - Thomas

0

一个简单的

LIMIT 1

在查询的末尾加上足够的条件即可仅返回最后一篇文章。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接