2016-08-05 3 views
1

"Mails"テーブルから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

あなたがそう自然にあなただけ – 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

は5つの結果が得られます '制限を5'使用しているストアドプロシージャ

それは 'mysql'の解決策ですか?私は 'phpmyadmin'を使用しています。 '#1054 - 'フィールドリスト 'に不明な列' m.mailaccountid 'のエラーがスローされます。 –

+0

解決策はmysqlであり、SQLコマンドラインとheidisqlで正常に動作します。私は読みやすさのためにテーブルエイリアスを使用していますが、mを削除しようとする可能性があります。接頭辞 –

+0

入力時にエラーが発生しました。今はうまくいく。ありがとうございました。 –

関連する問題