SQL WHERE IN,每个IN ID的结果有限且已排序

问题描述 投票:0回答:2

我不太知道如何描述,所以请原谅标题...

[我正在尝试编写一个函数,以在获取带有对话ID的数组时检索属于该对话的最新消息。

我的“消息”表如下:

id | conversationId | body           | createdDate
-------------------------------------------------------
1  | 1              | Hello          | 2020-06-09 01:01
2  | 1              | How are you?   | 2020-06-09 01:02
3  | 2              | Hi             | 2020-06-09 01:02
4  | 1              | I'm good, you? | 2020-06-09 01:03
5  | 2              | Hey there!     | 2020-06-09 01:04

我可以查询:

SELECT * FROM "message" WHERE "conversationId" IN (1, 2) ORDER BY "createdDate" DESC

按预期返回所有消息,这些消息与提供的对话ID匹配,并按最新createdDate排序。

我对如何将LIMIT仅包含每个createdDate的第一个结果(最近的conversationId)感到有些困惑。

我正在寻找的输出将是:

id | conversationId | body           | createdDate
-------------------------------------------------------
4  | 1              | I'm good, you? | 2020-06-09 01:03
5  | 2              | Hey there!     | 2020-06-09 01:04
sql postgresql select greatest-n-per-group
2个回答
0
投票

这是一个典型的每组最多n个问题。在Postgres中,一种简单有效的解决方法是distinct on


0
投票

您也可以使用窗口功能row_number

© www.soinside.com 2019 - 2024. All rights reserved.