简体   繁体   English

如何通过使用mysql降序获得每个组的5条记录?

[英]How to get 5 record of each group with order by descending using mysql?

I want to get 5 emails of every account of Inbox folder from "Mails" Table Table contain field of MailAccountID. 我想从“邮件”表格中获取Inbox文件夹的每个帐户的5封电子邮件。表格包含MailAccountID字段。

Table details:
Table Name: Mails
Folder field: FolderName
Email Account field: MailAccountID

I have tried solution suggested. 我试过建议的解决方案。 It works fine If I execute query in MySQL query window but it throw so many errors as Stored Procedure. 它工作正常如果我在MySQL查询窗口中执行查询但它会像存储过程那样抛出很多错误。

Stored Procedure: 存储过程:

CREATE PROCEDURE `SP_GetMailAccountData`()
BEGIN
    select * from
    (
    select m.*,
             if(m.mailaccountid <> @prev ,@rn:=1,@rn:=@rn+1) rn,
             @prev:=m.mailaccountid prev
    from     (select @rn:=0,@prev:='') p, mails m 
    where    foldername = 'inbox'
    order    by m.mailaccountid,m.dt desc
    ) s
    where   s.rn <= 3;
END

Error Screenshot: 错误截图: 在此输入图像描述

/*
create table mails(id int,mailaccountid int,foldername varchar(6),dt date);
truncate table mails;
insert into mails values
(1,1,'inbox','2016-08-01'),
(2,1,'inbox','2016-08-02'),
(3,1,'inbox','2016-08-03'),
(4,2,'outbox','2016-08-01'),
(5,2,'inbox','2016-08-02'),
(6,2,'inbox','2016-08-03'),
(7,3,'inbox','2016-08-01'),
(8,3,'outbox','2016-08-02'),
(9,3,'inbox','2016-08-03'),
(10,4,'inbox','2016-08-03'),
(10,4,'inbox','2016-08-03'),
(10,4,'inbox','2016-08-03'),
(10,4,'inbox','2016-08-04'),
(10,4,'inbox','2016-08-05')
;
*/
select * from
(
select m.*,
         if(m.mailaccountid <> @prev ,@rn:=1,@rn:=@rn+1) rn,
         @prev:=m.mailaccountid prev
from     (select @rn:=0,@prev:='') p, mails m 
where    foldername = 'inbox'
order    by m.mailaccountid,m.dt desc
) s
where   s.rn <= 3

result 结果

+------+---------------+------------+------------+------+------+
| id   | mailaccountid | foldername | dt         | rn   | prev |
+------+---------------+------------+------------+------+------+
|    3 |             1 | inbox      | 2016-08-03 |    1 |    1 |
|    2 |             1 | inbox      | 2016-08-02 |    2 |    1 |
|    1 |             1 | inbox      | 2016-08-01 |    3 |    1 |
|    6 |             2 | inbox      | 2016-08-03 |    1 |    2 |
|    5 |             2 | inbox      | 2016-08-02 |    2 |    2 |
|    9 |             3 | inbox      | 2016-08-03 |    1 |    3 |
|    7 |             3 | inbox      | 2016-08-01 |    2 |    3 |
|   10 |             4 | inbox      | 2016-08-05 |    1 |    4 |
|   10 |             4 | inbox      | 2016-08-04 |    2 |    4 |
|   10 |             4 | inbox      | 2016-08-03 |    3 |    4 |
+------+---------------+------------+------------+------+------+

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

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