2016-08-05 63 views
1

我想從「郵件」中獲得Inbox文件夾的每個帳戶的5封電子郵件表 表包含MailAccountID的字段。如何通過使用mysql降序來獲取每個組的5條記錄?

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

我嘗試瞭解決方案建議。它工作正常如果我在MySQL查詢窗口中執行查詢,但它會拋出像存儲過程那麼多的錯誤。

存儲過程:

CREATE PROCEDURE `SP_GetMailAccountData`() 
BEGIN 
    select * from 
    (
    select m.*, 
      if(m.mailaccountid <> @prev ,@rn:=1,@rn:[email protected]+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 

錯誤截圖: enter image description here

+0

您已經使用'限制5'所以很自然你只會得到5個結果 – Takarii

回答

0
/* 
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:[email protected]+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 

結果

+------+---------------+------------+------------+------+------+ 
| 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 | 
+------+---------------+------------+------------+------+------+ 
+0

是它的解決方案'mysql'?我正在使用'phpmyadmin'。它在'字段列表'中拋出錯誤#1054 - 未知列'm.mailaccountid'。請建議 –

+0

解決方案是mysql,並在sql命令行和heidisql中正常工作。我已經使用表別名來提高可讀性,您可以嘗試刪除m。前綴 –

+0

這是輸入錯誤。現在它工作正常。謝謝。 –

相關問題