sql - MySQL retrieve a maximum number of rows per distinct ID -
here's senario:
i have notes written people in table called notes
. each note has person_id
column identify note for.
i want retrieve last 5 notes written each person_id
in table.
so rather retrieving notes , using php extract last 5 each individual, can in 1 simple mysql query?
thanks in advance!
update
a few people have misunderstood question. i'll try explain better.
let's have 20 notes in notes
table. have 3 people in people
table. names jim, sally , randle
in notes
table, jim has 6 notes, sally has 9 notes , randle has 5 notes.
i want extract notes, limit 5 notes per person. out of 20 notes, want extract 15 of notes. 5 jim, 5 sally , 5 randle.
the below php , mysql example i want avoid - selecting rows table. when table gets 1,000,000 rows, that's lot of data process:
$notes_array = array(); $notes = $db->query("select person_id, notes notes"); foreach($notes $note) { // create array person's notes if (!isset($notes_array[$note->person_id])) $notes_array[$note->person_id] = array(); // if person has 5 notes, not need anymore if (count($notes_array[$note->person_id]) == 5) continue; // add note array $notes_array[$note->person_id][] = $note->notes; }
select a.* notes ( select count(*) notes b b.person_id = a.person_id , b.autonumber >= a.autonumber ) <= 5
change autonumber
auto incrementing field or datetime field taht can indicate how old record.
Comments
Post a Comment