查询只从具有相同值的多行中获取一行

时间:2013-08-12 13:16:03

标签: mysql sql isqlquery

我有一个通知表如下

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

此处user_sender是生成通知的人,user_receiver是获得通知的人,post_id是发布的ID,action可以是,评论等,如果接收器读取其他0

,则is_read为1

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

我正在使用的查询是

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,那么我只想要一行,这应该是最新的行。例如,用户喜欢一个帖子,一行添加到表中,然后用户不喜欢并再次喜欢,然后再添加一个新行,我只想要新行。

2 个答案:

答案 0 :(得分:4)

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

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()函数(或Postgres中的distinct on)。

编辑:

最大的身份:

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;

如果您想要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
             );

答案 1 :(得分: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