2016-08-05 6 views
1

Ich möchte 5 E-Mails von jedem Konto von Inbox Ordner von "Mails" Tabelle Tabelle enthalten Feld von MailAccountID.Wie bekomme ich 5 Datensätze jeder Gruppe mit der Reihenfolge, indem ich mit mysql absteige?

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

Ich habe versucht, Lösung vorgeschlagen. Es funktioniert gut Wenn ich Abfrage in MySQL-Abfrage-Fenster ausführen, aber es so viele Fehler wie Stored Procedure werfen.

Stored Procedure:

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 

Fehler Screenshot: enter image description here

+0

Sie verwendet haben 'Grenze 5' So werden Sie natürlich nur 5 Ergebnisse erhalten – Takarii

Antwort

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 

Ergebnis

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

Ist es Lösung von 'mysql'? Ich benutze 'phpmyadmin'. Es gibt einen Fehler von '# 1054 - Unbekannte Spalte 'm.mailaccountid' in 'Feldliste''. Bitte schlagen Sie –

+0

Lösung ist mysql und funktioniert gut in SQL-Befehlszeile und heidisql. Ich habe Tabellen Aliase für die Lesbarkeit verwendet, Sie könnten versuchen, die m zu entfernen. Präfix –

+0

Es war Tippfehler. Es funktioniert jetzt gut. Vielen Dank. –