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
491 views
in Technique[技术] by (71.8m points)

sql - MySQL: Limiting number of results received based on a column value | Combining queries

I've done research on this problem, but am having trouble finding a solution.

I have the following query that gives me a list of "some_id"s:

SELECT some_id FROM example GROUP BY some_id

And I have the following query that will get a list of the 5 most recent entries for a row that has "some_id" equal to a number.

SELECT * FROM example
WHERE some_id = 1
ORDER BY last_modified DESC
LIMIT 5

How can I get the the top 5 most recent entries from the table "example" for each "some_id", using only one query? If there are less than 5 entries for a "some_id", it is okay to include them, if that makes things less complex.

Many thanks!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Found the answer when looking at the first answer in the following post:

How do I limit the number of rows per field value in SQL?

I've modified it to fit my specific needs:

SELECT * FROM
(
    SELECT *, @num := if(@some_id = some_id, @num := @num + 1, 1) as row_num,
           @some_id := some_id as some_id
    FROM example
    ORDER BY last_modified DESC
) as e
WHERE row_num <= 5

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

...