簡體   English   中英

返回在一個列上不同但在另一列上排序的記錄

[英]Return records distinct on one column but order by another column

我正在用一個非常標准的消息模型構建一個Rails 3應用程序。 我想為每個唯一的session_id返回最近創建的消息記錄。 這似乎是一個相當簡單的任務,但我無法編寫代碼或找到可行的解決方案。
誠然,我也不是超級SQL精通者(到目前為止,我主要是通過Active Record查詢獲得的)。 這是我要完成的工作。

樣本消息表:

| id | sender_id | receiver_id | conversation_id | subject | body | created_at |
| 1  |     *     |      *      |        1        |    *    |   *  |    16:01   |
| 2  |     *     |      *      |        2        |    *    |   *  |    17:03   |
| 3  |     *     |      *      |        1        |    *    |   *  |    18:04   |
| 4  |     *     |      *      |        3        |    *    |   *  |    19:06   |
| 5  |     *     |      *      |        2        |    *    |   *  |    20:07   |
| 6  |     *     |      *      |        1        |    *    |   *  |    21:08   |
| 7  |     *     |      *      |        4        |    *    |   *  |    22:09   |

返回我想只得到最“近”的消息為每個記錄conversation_id並下令created_at DESC

| id | sender_id | receiver_id | conversation_id | subject | body | created_at |
| 7  |     *     |      *      |        4        |    *    |   *  |    22:09   |
| 6  |     *     |      *      |        1        |    *    |   *  |    21:08   |
| 5  |     *     |      *      |        2        |    *    |   *  |    20:07   |
| 4  |     *     |      *      |        3        |    *    |   *  |    19:06   |

我在SQLite中的原始解決方案工作得很好: GROUP BY (conversation_id) 但是,顯然該解決方案是SQLite獨有的,不適用於Postgres。

接下來,我嘗試了: SELECT DISTINCT ON (conversation_id) * 但是,這也需要我不想要的ORDER BY (conversation_id) 我想按created_at訂購。

DISTINCT ON

如果使用DISTINCT ON ,則需要一個子查詢:

SELECT *
FROM  (
   SELECT DISTINCT ON (conversation_id) *
   FROM   message t
   ORDER  BY conversation_id, created_at DESC
   ) sub
ORDER BY created_at DESC;

子查詢中的順序必須與DISTINCT ON子句中的列一致,因此您必須將其包裝在外部查詢中才能獲得所需的排序順序。

row_number()替代

類似的故事,您還需要一個子查詢:

SELECT id, sender_id, receiver_id, conversation_id, subject, body, created_at
FROM  (
   SELECT *, row_number() OVER (PARTITION BY conversation_id
                                ORDER BY created_at DESC) AS rn
   FROM   message t
   ) sub
WHERE  rn = 1
ORDER  BY created_at DESC;

也可能較慢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM