我不知道如何编写获取最后一条记录的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
答案 0 :(得分: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
请注意,这将过滤每个用户的最后一个通知,即私信,并且reply_id为零。
答案 1 :(得分:0)
一个简单的
LIMIT 1
在查询结束时应该只返回最后一篇文章。