Get the last record of each group of records

I do not know how to write SQL syntax to get the last record (according to a recent post and did not respond).

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 streaming notification, it should get the last record of each notification record and check has_replied 0if it is 0, then it should return it so that PHP can read if there is a notification that hasn been answered. So, it should return like this (pseudo):

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

If the second column indicates whether the last message was answered or not.

My current SQL syntax (works but doesn't get the last record, and if it answered):

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
+3
source share
2 answers
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

LIMIT 1

, .

0

All Articles