行数没有明显的

时间:2015-07-13 11:08:28

标签: mysql postgresql

我有这个问题:

SELECT DISTINCT ON (pair) *,
    CASE WHEN sender_id<recipient_id
      THEN (sender_id,recipient_id)
      ELSE (recipient_id,sender_id)
    END AS pair FROM "messages" WHERE 
    ((recipient_id = 6 and recipient_delete = false) or 
    (sender_id = 6 and sender_delete = false))  
    GROUP BY messages.id
    ORDER BY  pair, created_at, unread_count DESC

带来用户对话的最新消息(用户收件箱)。

现在我需要显示每个会话的未读消息总计数,表'打开'中有一个标志,表明消息是否未读。

这是我为它写的查询:

SELECT DISTINCT ON (pair) *,
    CASE WHEN sender_id<recipient_id
      THEN (sender_id,recipient_id)
      ELSE (recipient_id,sender_id)
    END AS pair, COUNT(messages.opened= false) AS unread_count FROM "messages" WHERE 
    ((recipient_id = 6 and recipient_delete = false) or 
    (sender_id = 6 and sender_delete = false))  
    GROUP BY messages.id
    ORDER BY  pair, created_at, unread_count DESC

但即使有超过2或3条消息,它也显示为1(我猜这是因为Distinct)。

有什么想法吗?

如果您需要知道我们为什么有用户CASE WHEN功能,请查看question

2 个答案:

答案 0 :(得分:1)

在您的查询中选择“messages.opened”字段(Alias messages_opened),然后将它们包围起来:

选择计数(messages_opened) FROM(... [您的查询])为A 其中A.messages_opened = false

查询示例:

DECLARE @table AS TABLE 
  ( 
     messageid   INT, 
     senderid    INT, 
     recipientid INT 
  ) 

INSERT INTO @table 
            (messageid, 
             senderid, 
             recipientid) 
VALUES      (1, 
             10, 
             20), 
            (2, 
             10, 
             20), 
            (3, 
             11, 
             20), 
            (4, 
             11, 
             20), 
            (5, 
             10, 
             20) 

SELECT Count(messageid) AS countOfMessages, 
       senderid, 
       recipientid 
FROM   @table 
GROUP  BY senderid, 
          recipientid 

答案 1 :(得分:1)

我有点困惑,因为你的逻辑似乎会带来最早的消息而不是最新消息。

虽然Jun 6 - 97 Jun 7 - 86.66 ... 非常强大,但我不确定你是否能随时获得你想要的东西。我倾向于切换到使用窗口函数:

distinct on