【发布时间】:2021-10-02 11:45:39
【问题描述】:
我在 postgresql 中有一个如下表:
id | chat_id | content | time | read_times
----+---------+-----------+------+-------------------------------------------------------------------------
1 | chat_10 | content_1 | t1 | [{"username": "user1", "time": 123}, {"username": "user2", "time": 111}]
2 | chat_10 | content_2 | t2 | [{"username": "user2", "time": 1235}]
3 | chat_10 | content_3 | t3 | []
4 | chat_11 | content_4 | t4 | [{"username": "user1", "time": 125}, {"username": "user3", "time": 121}]
5 | chat_11 | content_5 | t5 | [{"username": "user1", "time": 126}, {"username": "user3", "time": 127}]
注意:t1 < t2 < t3 < t4 < t5
每个用户阅读一条消息后,我们将其注册到read_times 列(user2 在时间1235 阅读了一条 id 为2 的消息),现在我想获取带有未读计数聊天的用户聊天列表。对于user1,结果如下:
chat_id | content | unread_count
--------+-----------+--------------
chat_10 | content_3 | 2
chat_11 | content_5 | 0
注意:unread_count 是用户未在caht_id 中阅读的消息数。
一个查询可以吗?
【问题讨论】:
-
你能解释一下专栏
unread_count吗? -
似乎
user1的“未读计数”考虑了任何不包括"username": "user1"的行。 -
还不清楚,为什么
user1,在chatid 10和内容3中,unread_count是2??
标签: sql postgresql group-by window-functions postgresql-13