简体   繁体   English

MySQL为每个不同的ID检索最大行数

[英]MySQL retrieve a maximum number of rows per distinct ID

Here's my senario: 这是我的senario:

I have notes written about people in a table called notes . 我在桌子上有一个关于人的notes称为notes Each note has a person_id column to identify who the note is for. 每个注释都有一个person_id列,用于标识注释的对象。

I want to retrieve the last 5 notes written for each person_id in the table. 我想检索为表中每个person_id编写的最后5条注释。

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? 因此,除了检索所有注释并使用PHP为每个人提取最后五个注释之外,我还可以在一个简单的MySQL查询中执行此操作吗?

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. 假设我的notes表中有20个笔记。 I then have 3 people in my people table. 然后,我的people表中有3个人。 Their names are Jim, Sally and Randle 他们的名字叫吉姆,莎莉和兰德

In the notes table, Jim has 6 notes, Sally has 9 notes and Randle has 5 notes. notes表中,Jim有6个注释,Sally有9个注释,Randle有5个注释。

I want to extract all their notes, but limit it to 5 notes per person. 我想提取所有笔记,但每人限制为5个笔记。 So out of the 20 notes, I want to extract 15 of those notes. 因此,我要从20个笔记中提取15个笔记。 5 for Jim, 5 for Sally and 5 for Randle. 吉姆(Jim)5,萨莉(Sally)5,兰德(Randle)5。

The below PHP and MySQL example is what I want to avoid - selecting all rows from the table. 下面是我想避免的 PHP和MySQL示例-从表中选择所有行。 When the table gets to 1,000,000 rows, that's a lot of data to process: 当表达到1,000,000行时,将处理大量数据:

$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. AUTONUMBER更改为自动递增字段,或者日期时间字段可以指示记录的AUTONUMBER

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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