为多条记录返回 PostgreSQL 中的最新条目

Returning the latest entries in PostgreSQL for multiple records

我有一个网络应用程序,用户可以在其中向存储在数据库中的联系人发送消息。成功发布消息后,收件人的详细联系信息将输入另一个 table。我想查询 return 该邮件的收件人。这些是 table:

上的列
| communication_id | first_name | last_name | telephone |

communication_id 是一个外键,它对于每个不同的通信都是不同的,而不是每个人。例如,如果用户发送一条消息并且有 20 个收件人,我只想得到这 20 个。所有 20 个都具有相同的 communication_id

我目前的查询是

SELECT communication_id, first_name ||' ' || last_name AS recipient_name, telephone
FROM communications_sent
ORDER BY communication_id DESC

但众所周知,这将 return 一切。我也不能 LIMIT 因为有些条目会被遗漏。我不能使用 COUNT(*)>1,因为即使是较早的通信也有大于 1 的计数。我怎样才能只获得最新的条目?可以是1条,也可以是100条。

我上面查询的示例输出是:

|communication_id|recipient_name|telephone|
|       263      |   John Doe   |712100100|
|       263      |   Willy Bill |721001001|
|       262      |   Mary May   |700101010|
|       262      |   Joe Jimmy  |722111000|

如果我没理解错的话,您只需要一个通信 ID,但需要所有收件人。如果是:

SELECT cs.communication_id, cs.first_name ||' ' || cs.last_name AS recipient_name, cs.telephone
FROM communications_sent cs
WHERE cs.communication_id = (SELECT MAX(cs2.communication_id)
                             FROM communications_sent cs2
                            )
ORDER BY cs.communication_id DESC