Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

mysql - Sorting groups of data looking at the newest entry

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

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

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...