Select Earliest Date and Time from List of Distinct User Sessions

前端 未结 2 1150
伪装坚强ぢ
伪装坚强ぢ 2021-01-20 09:58

I have a table of user access sessions which records website visitor activity:

accessid, userid, date, time, url

I\'m trying to retrieve all dis

2条回答
  •  -上瘾入骨i
    2021-01-20 10:17

    This is a variation of the "greatest-n-per-group" problem that comes up on StackOverflow several times per week.

    SELECT 
            a1.accessid, 
            a1.date, 
            a1.time 
    FROM 
            accesslog a1
    LEFT OUTER JOIN
            accesslog a2
      ON (a1.accessid = a2.accessid AND a1.userid = a2.userid
        AND (a1.date > a2.date OR a1.date = a2.date AND a1.time > a2.time))
    WHERE a1.userid = '1234'
      AND a2.accessid IS NULL;
    

    The way this works is that we try to find a row (a2) that has the same accessid and userid, and an earlier date or time than the row a1. When we can't find an earlier row, then a1 must be the earliest row.


    Re your comment, I just tried it with the sample data you provided. Here's what I get:

    +----------+------------+----------+
    | accessid | date       | time     |
    +----------+------------+----------+
    |        1 | 2009-08-15 | 01:01:01 | 
    |        2 | 2009-09-01 | 14:01:01 | 
    +----------+------------+----------+
    

    I'm using MySQL 5.0.75 on Mac OS X.

提交回复
热议问题