获取每个记录组的最后一条记录
我不知道如何编写获取最后一条记录的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
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为零。
假设你认为'LEFT OUTER JOIN'或'INNER JOIN'会比'JOIN'好?如我错了请纠正我。 – MacMac 2011-05-09 21:04:27
@lolwut - 'Join'是'Inner Join'的缩写。同样,“左连接”是“左外连接”的缩写。但是,是否使用左连接与内连接取决于您正在尝试完成的工作。如果你想要所有成员是否有通知,那么我需要将Where子句中的条件移动到UserLastNotification的On子句中。 – Thomas 2011-05-09 21:09:29
没关系。都很好。谢谢。 :-) – MacMac 2011-05-09 21:12:08
简单
LIMIT 1
在查询到底应该足以只返回最后一篇文章。
+1。我喜欢桌子格式':)' – 2011-05-09 20:39:24
很高兴你喜欢它。 – MacMac 2011-05-09 20:39:55
伪输出中的第三列是什么? – 2011-05-09 20:47:03