选择匹配session_id的最新记录

时间:2009-03-11 19:10:51

标签: sql mysql

我应该在关系数据库类中多加注意,所以我需要一些帮助。

我有一个像这样结构的表格(还有更多,但我只发布相关信息):

+------------------+-------------+------+-----+-------------------+-------+
| Field            | Type        | Null | Key | Default           | Extra |
+------------------+-------------+------+-----+-------------------+-------+
| session_id       | char(32)    | NO   |     | NULL              |       |
| file             | varchar(30) | NO   |     | NULL              |       |
| access_time      | timestamp   | NO   |     | CURRENT_TIMESTAMP |       |
+------------------+-------------+------+-----+-------------------+-------+`

我想为每个file选择access_time最大session_id的记录的{{1}}字段。几乎是每个会话中访问的最后一页。

我尝试了无数DISTINCT和GROUP BY子句的组合,但由于某种原因,我似乎无法绕过它。我正在使用MySQL。请帮助。

3 个答案:

答案 0 :(得分:2)

select * from my_table t1
    where t1.access_time = (
       select max(t2.access_time) 
         from my_table t2 
         where t2.session_id = t1.session_id
       )

答案 1 :(得分:1)

我知道这可以在SQL Server中运行,它应该移植到MySQL。

select session_id, timestamp, file 
from table t1
join (select session_id, max(timestamp) as timestamp) 
        from table group by session_id) as t2
   on t1.session_id = t2.session_id
     and t1.timestamp = t2.timestamp

答案 2 :(得分:0)

SELECT
     T1.session_id,
     T1.file,
     T1.access_time
FROM
     My_Table T1
LEFT OUTER JOIN My_Table T2 ON
     T2.session_id = T1.session_id AND
     T2.access_time > T1.access_time
WHERE
     T2.session_id IS NULL

如果同一session_id存在重复的access_time值,则可能会为该session_id获取多行。根据您针对该情况的业务规则,您可以根据需要调整此项以避免这种情况。