计算最后关联记录具有负属性的位置

时间:2014-04-26 16:47:00

标签: sql postgresql aggregate-functions greatest-n-per-group

我有两个表,conversationmessage(会话有很多消息)。

conversation:
  - id

message:
  - id
  - conversation_id
  - created_at
  - read (boolean)

我想计算最后一次(按message.created_at排序}消息的read属性为false的对话。

1 个答案:

答案 0 :(得分:2)

按照概述得到的计数:

SELECT count(*) AS msg_ct
FROM  (
   SELECT DISTINCT ON (conversation_id) *
   FROM   messages
   ORDER  BY conversation_id, created_at DESC
   ) sub
WHERE NOT read;

您根本不需要在此处包含父表conversation

子查询返回每个对话的最后一行("ordered by messages.created_at") 详情请点:Select first row in each GROUP BY group?
外部查询计算readFALSE的位置。

替代NOT EXISTS

SELECT count(*) AS msg_ct
FROM   messages m
WHERE  NOT read
AND NOT EXISTS (
   SELECT 1
   FROM   messages m1
   WHERE  m1.conversation_id = m.conversation_id
   AND    m1.created_at > m.created_at
   );

大桌子可能会更快。您必须使用EXPLAIN ANALYZE进行测试。