2012-09-19 38 views
0

我有一個表的數據如下SQL - 得到表最新記錄,其中域是唯一

id status conversation_id message_id date_created 
1  1   1     72   2012-01-01 00:00:00 
2  2   1     87   2012-03-03 00:00:00 
3  2   2     95   2012-05-05 00:00:00 

我想在date_created DESC爲了一切從表中的行,但只佔一行conversation_id 。所以在上面的示例數據的情況下,我想要得到的行與id 2和3.

任何意見是非常感謝。

回答

1

參見SQL Fiddle

SELECT T.* 
FROM T 
WHERE NOT EXISTS (
    SELECT * 
    FROM T AS _T 
    WHERE _T.conversation_id = T.conversation_id 
    AND (
    _T.date_created > T.date_created 
    OR 
    _T.date_created = T.date_created AND _T.id > T.id) 
) 
ORDER BY T.date_created DESC 

得到

ID  STATUS CONVERSATION_ID MESSAGE_ID DATE_CREATED 
3   2   2    95   May, 05 2012 
2   2   1    87   March, 03 2012 
2
SELECT t.id, t.status, t.conversation_id, t.message_id, t.date_created 
    FROM YourTable t 
     INNER JOIN (SELECT conversation_id, MAX(date_created) AS MaxDate 
         FROM YourTable 
         GROUP BY conversation_id) q 
      ON t.conversation_id = q.conversation_id 
       AND t.date_created = q.MaxDate 
    ORDER BY t.date_created DESC; 
+0

人常常使用這個連接與 - GROUP_BY和-MAX模式,但不幸的是,這是錯誤的。如果有幾個具有相同conversation_id和date_created的記錄 - 它將全部返回。請參閱http://sqlfiddle.com/#!2/6f3cb/3 – Incidently

0

創建和插入件從@Incidently借:

CREATE TABLE T 
(id int, status int, conversation_id int, message_id int, date_created datetime); 

insert into T (id, status, conversation_id, message_id, date_created) 
values(1,  1,   1,     72,   '2012-01-01 00:00:00'); 
insert into T (id, status, conversation_id, message_id, date_created) 
values(2,  2,   1,     87,   '2012-03-03 00:00:00'); 
insert into T (id, status, conversation_id, message_id, date_created) 
values(3,  2 ,  2 ,     95 ,   '2012-05-05 00:00:00'); 

假設的ID是主鍵然後這個SOLV ES的問題,通過@Incidentally中指出@喬的回答是:

select T.* 
from 
    T 
    inner join (
     select conversation_id, max(id) as id 
     from T 
     group by conversation_id 
    ) s on s.id = T.id 
order by T.date_created desc, T.conversation_id 
; 
+------+--------+-----------------+------------+---------------------+ 
| id | status | conversation_id | message_id | date_created  | 
+------+--------+-----------------+------------+---------------------+ 
| 3 |  2 |    2 |   95 | 2012-05-05 00:00:00 | 
| 2 |  2 |    1 |   87 | 2012-03-03 00:00:00 | 
+------+--------+-----------------+------------+---------------------+