2013-12-17 92 views
0

我有一個元數據表看起來像這樣的:查找最高值列各組

+----------------------------+ 
|  metadata   | 
+----+----------+------------+ 
| id | group_id | message_id | 
+----+----------+------------+ 
| 1 | 1  |  5  | 
+----+----------+------------+ 
| 2 | 2  |  6  | 
+----+----------+------------+ 
| 3 | 1  |  8  | 
+----+----------+------------+ 
| 4 | 2  |  10  | 
+----+----------+------------+ 

對於每個group_id,我想選擇具有最高id 行所以我想回來:

+----------------------------+ 
|   results   | 
+----+----------+------------+ 
| id | group_id | message_id | 
+----+----------+------------+ 
| 3 | 1  |  8  | 
+----+----------+------------+ 
| 4 | 2  |  10  | 
+----+----------+------------+ 

我在想這將是這樣的事情,但以下只返回行4。從我想選擇MAX(metadata.id)

SELECT 
    MAX(metadata.id) 
FROM 
    metadata 
GROUP BY 
    metadata.message_id 

假設Metadatum是一個ActiveRecord模型組,每組,並groupbelongs_to關係,你將如何構建這個查詢與AR?

回答

0

產生的預期結果查詢(假設id是唯一的):

SELECT t1.* FROM t AS t1 
JOIN (
    SELECT max(id) AS id FROM t 
    GROUP BY group_id 
) t2 ON t1.id = t2.id 

輸出:

| ID | GROUP_ID | MESSAGE_ID | 
|----|----------|------------| 
| 3 |  1 |   8 | 
| 4 |  2 |   10 | 

小提琴here

但是,我不完全明白你的意思是由AR查詢。要做到這一點

+0

通過AR我的意思是活動記錄查詢(即使用活動記錄方法構建的查詢)。 – dyln

1

一種方法是使用row_number()

SELECT m.id 
FROM (select m.*, 
      row_number() over (partition by m.message_id order by m.id desc) as seqnum 
     from metadata m 
    ) m 
WHERE seqnum = 1; 

在Postgres裏,你也可以用distinct on做到這一點:

select distinct on (m.message_id), m.id 
from metadata m 
order by m.message_id, m.id; 
0

正如編程的樂趣,這裏是另一種解決方案

SELECT t1.* 
FROM metadata AS t1 
WHERE t1.id = (
    SELECT t2.id 
    FROM metadata AS t2 
    WHERE t2.group_id = t1.group_id 
    ORDER BY t2.id DESC 
    LIMIT 1 
)