I am implementing notification system. My table structure is somewhat like this..
id (auto increment primary key)
user_id (user id of the user whom the notification should be shown, int)
triggered_by (user who triggered the notification, int)
post_id (post for which the notification exists, int)
type (type of the notification, int)
seen (has the notification been read, bool)
When I am marking a notification as seen, I am using post_id and type, that means we can safely assume that if the row with largest id is seen, all the previous rows for that post_id and type would be seen.
now, I want to fetch rows combined with previous entries for that post_id and type, plus a count of rows registered for that post_id and type. My current query is
select max(x.id) as id,
x.post_id as post_id,
x.seen as seen,
x.user_id as user_id,
x.triggered_by as triggered_by,
x.type as type,
x.count as count
from (SELECT notification.id,
notification.post_id,
notification.user_id,
notification.triggered_by,
notification.type,
c.count, notification.seen
FROM `notification`
join (select post_id, type, count(id) as count
from notification group by post_id, type) c
on c.type=notification.type
and c.post_id=notification.post_id
Where notification.user_id=1) x
Group by post_id
Order by id desc limit 10
The problem with this query is that the 'group by' clause of the outer most query is returning any random row's 'seen' column where as I want it to return data other then count from the row with the largest id.