2011-06-11 38 views
1

行數:組通過,但指定我有以下每分組ID

id | name | Book Read  | Date Read 
1 Maria Dogs love cats  12/31/2008 
1 Maria Cats and Dogs  12/31/2007 
1 Maria Cowboys   12/31/2006 
2 Tom  Cowboys   12/31/2008 
2 Tom  Indians   12/31/2005 
2 Tom  Cats and Dogs  12/31/2003 
3 Harry Raining hard  12/31/2005 
3 Harry Cats and Dogs  12/31/2002 
3 Harry Indians   12/31/2001 

如果我不 「SELECT * FROM表GROUP BY ID」,我得到:

id | name | Book Read   | Date Read 
1 Maria Dogs love cats  12/31/2008 
2 Tom  Cowboys    12/31/2008 
3 Harry Raining hard  12/31/2005 

但如何我能爲每個人獲得前兩本書嗎?即:

id | name | Book Read   | Date Read 
1 Maria Dogs love cats  12/31/2008 
1 Maria Cats and Dogs  12/31/2007 
2 Tom  Cowboys    12/31/2008 
2 Tom  Indians    12/31/2005 
3 Harry Raining hard  12/31/2005 
3 Harry Cats and Dogs  12/31/2002 
+0

的SQL將是很長的,醜陋的,無法讀取。我認爲更好的選擇是獲取所有數據並用外部語言處理它們。 – Michas 2011-06-12 14:55:50

回答

0

假設你有一個自動增量場,在我的例子叫我

select * from table as t1 
where (select count(*) from table as t2 
     where t1.id = t2.id and t2.i < t1.i) <2 

這是另一種選擇

select tmp.i,tmp.id,tmp.name,tmp.book_read 
from (
    select 
    id,i,name,book_read, 
    if(@prev <> id, @r:=1,@r:[email protected]+1) as rank, 
    @prev := id 
    from table as t 
    join (select @r:=null,@prev:=0) as rn 
    order by t.id,t.i 
) as tmp 
where tmp.rank <= 2 
order by i,id; 
+0

我想你在自動增量領域失去了我。我如何在我的例子中使用這些字段? – 2011-06-11 18:28:17

+0

如果您沒有自動增量字段,您如何爲每個組指定兩條記錄? – 2011-06-11 19:29:45

+0

我在上面展示了我的例子。我沒有上面的自動增量字段 – 2011-06-11 21:42:18