简体   繁体   中英

MySQL retrieve a maximum number of rows per distinct ID

Here's my senario:

I have notes written about people in a table called notes . Each note has a person_id column to identify who the note is for.

I want to retrieve the last 5 notes written for each person_id in the table.

So rather than retrieving ALL notes and using PHP to extract the last five for each individual, can I do this in one simple MySQL query?

Thanks in advance!

UPDATE

A few people have misunderstood my question. I'll try explain better.

Let's say I have 20 notes in my notes table. I then have 3 people in my people table. Their names are Jim, Sally and Randle

In the notes table, Jim has 6 notes, Sally has 9 notes and Randle has 5 notes.

I want to extract all their notes, but limit it to 5 notes per person. So out of the 20 notes, I want to extract 15 of those notes. 5 for Jim, 5 for Sally and 5 for Randle.

The below PHP and MySQL example is what I want to avoid - selecting all rows from the table. When the table gets to 1,000,000 rows, that's a lot of data to process:

$notes_array = array();

$notes = $db->query("SELECT person_id, notes FROM notes");
foreach($notes AS $note) {

    // Create an array for this person's notes
    if (!isset($notes_array[$note->person_id]))
        $notes_array[$note->person_id] = array();

    // If this person has 5 notes, we do not need anymore
    if (count($notes_array[$note->person_id]) == 5)
        continue;

    // Add note to an array
    $notes_array[$note->person_id][] = $note->notes;

}
select  a.*
from    NOTES a
where 
(
    select  count(*) 
    from    NOTES as b
    where   b.Person_ID = a.Person_ID and b.AutoNumber >= a.AutoNumber
) <= 5

change AUTONUMBER to your auto incrementing field or a datetime field taht can indicate how old is the record.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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