我有两个表,conversation
和message
(会话有很多消息)。
conversation:
- id
message:
- id
- conversation_id
- created_at
- read (boolean)
我想计算最后一次(按message.created_at
排序}消息的read
属性为false
的对话。
答案 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?
外部查询计算read
为FALSE
的位置。
替代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
进行测试。