繁体   English   中英

获取每个用户每个类别的最新记录

[英]get last record of each user for each category

我想获取每个类别的每个用户的最新记录。

例如我有一张桌子

测试(test_id,cat_id,user_id,得分,时间)

我需要每个用户的每个类别的最新记录。 我可以按category_id或user_id来使用group,但是我没有得到如何获得所需结果的方法?

例如我有以下记录

test_id | cat_id | user_id | score | time
      1 |      1 |      11 |    20 | 2016-11-12 01:11:11
      2 |      2 |      11 |    24 | 2016-11-12 01:11:11
      3 |      1 |      12 |    25 | 2016-11-12 01:11:11
      4 |      3 |      12 |    21 | 2016-11-12 01:11:11
      5 |      1 |      13 |    22 | 2016-11-12 01:11:11
      6 |      2 |      12 |    23 | 2016-11-12 01:11:11
      7 |      2 |      12 |    27 | 2016-11-12 01:11:11
      8 |      1 |      11 |    21 | 2016-11-12 01:11:11

现在我需要以下结果

test_id | cat_id | user_id | score | time
      2 |      2 |      11 |    24 | 2016-11-12 01:11:11
      3 |      1 |      12 |    25 | 2016-11-12 01:11:11
      4 |      3 |      12 |    21 | 2016-11-12 01:11:11
      5 |      1 |      13 |    22 | 2016-11-12 01:11:11
      7 |      2 |      12 |    27 | 2016-11-12 01:11:11
      8 |      1 |      11 |    21 | 2016-11-12 01:11:11

在上面的o / p中,每个用户唯一的最后结果就是每个类别的到来。

您需要的查询是:

SELECT l.test_id, l.cat_id, l.user_id, l.score, l.time
FROM tests l                     # "l" from "last"
LEFT JOIN tests n                # "n" from "next"
    ON l.user_id = n.user_id     # match user
    AND l.cat_id = n.cat_id      # and category
    AND l.time <= n.time         # "next" is not before "last" (check the time)
    AND l.test_id < n.test_id    # "next" is after "last" when the times are equal
WHERE n.test_id IS NULL          # there is no "next" matching the JOIN conditions

这个怎么运作

查询联接test别名为l (从“最后”)对本身别名为n (从“下一步”后,“最后”)。 LEFT JOIN确保来自l所有行都包含在LEFT JOIN中。 l每一行与n中的所有行配对,这些行包含相同的user_idcat_id (“每个用户,每个类别”),并且timetest_id列的值更大。 因为从技术上来说,在user_idcat_idtime列中具有两行具有相同值的行在技术上是可能的,所以将l的行与n的行相等地匹配到稍后在数据库中输入的行(它具有更大的auto-incremented test_id ) 。

当在n找不到满足所有ON条件的行时,来自l的行将与充满NULL的行配对。

WHERE条件仅在n.test_id保留具有NULL的行。 它们是l中不匹配n (因为n中没有行在time列中具有较大的值或在时间相等时具有较大的test_id )。 这些是每对(用户,类别)对的最后记录。

试试这个SELECT MAX(user_id) FROM tests GROUP BY cat_id

在这里,我们需要所有类别的最后一个用户。 因此,我们必须按类别进行分组,并找到时间最长的用户。

SELECT t1.* 
FROM tests t1
INNER JOIN
(
    SELECT max(time) MaxTime,user_id,cat_id
    FROM tests
    GROUP BY user_id,cat_id
) t2
  ON t1.user_id = t2.user_id
  AND t1.cat_id = t2.cat_id
  AND t1.time = t2.MaxTime
order by t1.time desc

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM