簡體   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