MySQL内部联接只选择1行

时间:2019-01-21 21:26:30

标签: mysql sql

我有一个网站访问日期表(sampleTable),以年-月-日为单位,时间戳为年-月-日小时-分钟-秒,用户ID和网站访问ID。我想选择与最近一天发生的首次访问相对应的访问ID。到目前为止,我已经尝试过

select userID, MAX(dayAccessed) as latestDay from sampleTable group by userID;

,它返回最近的一天。然后,我在内部联接中使用了此命令,以使该查询与原始表重新联接,原始表正确地对列进行了排序。我的问题是我无法以两个用户ID的身份在最近一天访问最早的访问ID

SELECT sampleTable.dayTimeAccessed, sampleTable.userID, latest.latestDay 
FROM 
    (SELECT userID, MAX(dayTimeAccessed) AS latestDay 
    from sampleTable 
    group by userID) AS latest 
INNER JOIN sampleTable 
ON sampleTable.userID = latest.userID AND 
    sampleTable.dayTimeAccessed 
limit 1;

仅返回与第一个userID匹配的一个字段。

1 个答案:

答案 0 :(得分:2)

您需要先找到MAX日期,然后是MIN时间戳:

SELECT 
   min(sampleTable.dayTimeAccessed) -- min timestamp per user for the MAX date
  ,latest.userID
  ,latest.latestDay 
FROM 
  ( SELECT userID, MAX(dayAccessed) AS latestDay  -- max date per user
    from sampleTable 
    group by userID
  ) AS latest 
INNER JOIN sampleTable 
ON sampleTable.userID = latest.userID
AND sampleTable.dayAccessed = latest.latestDay
GROUP BY latest.userID, latest.latestDay

对于MySQL 8,您可以使用ROW_NUMBER:

SELECT *
FROM
 (
   SELECT *, 
      ROW_NUBMER() -- min timestamp per user for the MAX date
      OVER (PARTITION BY userID
            ORDER BY dayAccessed DESC, dayTimeAccessed ASC) AS rn
   FROM sampleTable
 ) t
WHERE rn = 1;