[英]mysql select latest timestamp in a group
我有一個表,我想在表中選擇一個特定列的值定義的類別中的最新時間戳。
特別
SELECT *
FROM takelist
WHERE producer_name = 'sean'
AND bucket_id = '2CCEx15_1o'
結果是
+-------------+---------------+------------+---------------------+
| takelist_id | producer_name | bucket_id | ts |
+-------------+---------------+------------+---------------------+
| 1 | sean | 2CCEx15_1o | 2013-10-07 18:29:00 |
| 4 | sean | 2CCEx15_1o | 2013-10-07 18:33:09 |
| 5 | sean | 2CCEx15_1o | 2013-10-07 18:33:38 |
| 27 | sean | 2CCEx15_1o | 2013-10-07 18:37:38 |
| 212 | sean | 2CCEx15_1o | 2013-10-14 18:36:05 |
| 236 | sean | 2CCEx15_1o | 2013-10-21 17:59:56 |
| 237 | sean | 2CCEx15_1o | 2013-10-21 18:00:55 |
| 281 | sean | 2CCEx15_1o | 2013-10-29 15:58:40 |
| 287 | sean | 2CCEx15_1o | 2013-10-29 19:24:15 |
| 330 | sean | 2CCEx15_1o | 2013-10-31 14:39:33 |
| 615 | sean | 2CCEx15_1o | 2013-12-16 22:46:59 |
| 616 | sean | 2CCEx15_1o | 2013-12-16 22:54:46 |
+-------------+---------------+------------+---------------------+
我想為名為bucket_id的列的每個唯一值選擇一行,其中所選行具有最新的時間戳。
我根據之前對類似問題的回答嘗試過以下,但一定有錯
SELECT takes.* FROM takelist as takes
INNER JOIN (
SELECT takelist_id, max(ts) max_ts, bucket_id
FROM takelist
WHERE producer_name='sean'
GROUP BY bucket_id
) latest_take
ON takes.takelist_id=latest_take.takelist_id
AND takes.ts=latest_take.max_ts
您的查詢已結束。 但是您使用的是id而不是時間戳:
SELECT takes.*
FROM takelist takes INNER JOIN
(SELECT max(ts) as max_ts, bucket_id
FROM takelist
WHERE producer_name = 'sean'
GROUP BY bucket_id
) latest_take
ON takes.ts = latest_take.max_ts and takes.bucket_id = latest_take.bucket_id;
在原始公式中選擇任意takelist_id
。 它可能不是你想要的那個。
嘗試這個:
SELECT t.*
FROM takelist AS t
INNER JOIN (SELECT MAX(ts) max_ts, bucket_id
FROM takelist WHERE producer_name='sean'
GROUP BY bucket_id
) lt ON t.bucket_id=lt.bucket_id AND t.ts=lt.max_ts;
要么
SELECT *
FROM (SELECT * FROM takelist WHERE producer_name='sean' ORDER BY bucket_id, ts DESC) A
GROUP BY bucket_id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.