开发者

Get last record of each record group

I don't know how to write the SQL syntax of getting the last record (according to recent post and is not replied to).

My table

+-------------------+-----------------------+------+-----+---------+----------------+
| 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       |                |
+-------------------+-----------------------+------+-----+---------+----------------+

Basically for each threaded notification, it should get the last record of each notification record and check if has_replied is 0, if it is 0 then it should return it so PHP can read whether there is a notification that hasn't been replied to. So like, it should return like this (pseudo):

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

Where the second column represents if the last post has been replied to or not.

My current SQL syntax (works but does not get the last record and if it's replie开发者_如何学Pythond to):

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

Note that this will filter on each user's last notification being a private message and having a reply_id being zero.


A simple

LIMIT 1

at the end of the query should be sufficient to only return the last post.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜