Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a table with two columns team and date. The date column has the date that the entry was added to the table.

I want to print the last 10 entries of each team sorted by date DESC. I also want to sort these groups of team entries by date DESC.

I tried a lot of things, but with no luck. It worked, but with 2 queries which is not acceptable in this case.

How can I do this with a single query? I have the feeling that this is a really newbie question.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
175 views
Welcome To Ask or Share your Answers For Others

1 Answer

SELECT rows.team, rows.date FROM (
  SELECT team, date,
    IF( @prev <> team, @rownum := 1, @rownum := @rownum+1 ) AS rownum,
    @prev := team
  FROM my_table
  JOIN (SELECT @rownum := NULL, @prev := 0) AS init
  ORDER BY team, date DESC
) AS rows
WHERE rownum <= 10

We make a temporary (virtual) table in the sub-query with rows ordered by team, date DESC and we start from the top giving an incrementing row number to each row and whenever team changes we reset the row number, then in the outer query we filter out any row that has row number greater than 10.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...