4

我有一个通知表如下

|id|user_receiver|user_sender|post_id|action|date|is_read

user_sender是生成通知的人,user_receiver是收到通知的人,post_id是帖子的ID,action可以是喜欢,评论等,is_read如果接收者读取则为1,否则为0

我想获取登录用户的所有通知

我正在使用的查询是

SELECT id, user_receiver, user_sender, post_id, action, 
 max(date) as date, is_read 
FROM notification 
WHERE user_receiver=$ses_user 
group by user_sender, action,post_id,is_read 
order by date desc

但即使我正在使用它也没有给我最新的行,max(date)而且我还想获​​得未读通知的数量。

如果有多行具有相同的 post_id、user_sender 和 action 并且应该是最新的,我只想要一行。例如一个用户喜欢一个帖子,一行被添加到表中,然后用户又不喜欢和喜欢,然后再次添加一个新行,我只想要新行。

4

2 回答 2

4

要获取 MySQL 中的最新行,您需要使用joinor 相关子查询:

SELECT id, user_receiver, user_sender, post_id, action, date, is_read
FROM notification n
WHERE user_receiver=$ses_user and
      date = (select max(date)
              from notification n2
              where n2.user_sender = n.user_sender and
                    n2.action = n.action and
                    n2.post_id = n.post_id and
                    n2.is_read = n.is_read
             )
order by date desc;

在其他数据库中,您只需使用该row_number()函数(或distinct on在 Postgres 中)。

编辑:

对于最大的 id:

SELECT id, user_receiver, user_sender, post_id, action, date, is_read
FROM notification n
WHERE user_receiver=$ses_user and
      id   = (select max(id)
              from notification n2
              where n2.user_sender = n.user_sender and
                    n2.action = n.action and
                    n2.post_id = n.post_id
             )
order by date desc;

如果您想要 where 的行数isread = 1,那么您可以执行以下操作:

SELECT sum(is_read = 1)
FROM notification n
WHERE user_receiver=$ses_user and
      id   = (select max(id)
              from notification n2
              where n2.user_sender = n.user_sender and
                    n2.action = n.action and
                    n2.post_id = n.post_id
             );
于 2013-08-12T13:19:27.343 回答
1

希望这篇文章会有所帮助,有一个带有插图的示例查询:

SELECT 
    BookId, 
    BookName, 
    BookCategory, 
    BookReferenceNumber, 
    COUNT( BookReferenceNumber ) AS HowManyRecs, 
    BookDetails, 
    BookStatus
FROM 
    tbl_BOOKS
WHERE (
    BookReferenceNumber LIKE '42324%'
    OR BookName LIKE '%42324%'
)    
AND (
    BookStatus = 'Available'
)
GROUP BY 
    BookReferenceNumber
HAVING (
    HowManyRecs > 0
)

(取自techqube.blogspot.in

于 2013-12-17T16:54:00.503 回答