0

次のようなデータのテーブルがあります

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

テーブルからすべての行を DESC 順に取得したいのですdate_createdが、1 行につき 1 行だけconversation_idです。id上記の例のデータの場合、 2 と 3の行を取得したいと思います。

どんなアドバイスでも大歓迎です。

4

3 に答える 3

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;
于 2012-09-19T15:39:53.557 に答える
1

SQL フィドルを参照してください

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 
于 2012-09-19T15:53:34.107 に答える
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が主キーであるとすると、これにより、@Joeの回答で@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 |
+------+--------+-----------------+------------+---------------------+
于 2012-09-19T16:30:47.477 に答える