2013-07-19 81 views
0

我有一個包含不同類別的表。是否有可能從每個類別返回兩個隨機行?SQL:從每個類別獲取2行

我的表:

----------------------------- 
| ID | CATEGORY    | 
----------------------------- 
| 1 | PINK     | 
| 2 | GREEN    | 
| 3 | PINK     | 
| 4 | GREEN    | 
| 5 | BLUE     | 
| 6 | BLUE     | 
| 7 | BLUE     | 
| 8 | PINK     | 
| 9 | GREEN    | 
----------------------------- 

我要輸出什麼:

----------------------------- 
| ID | CATEGORY    | 
----------------------------- 
| 1 | PINK     | 
| 8 | PINK     | 
| 2 | GREEN    | 
| 4 | GREEN    | 
| 6 | BLUE     | 
| 7 | BLUE     | 
----------------------------- 
+0

是的。這是可能的http://stackoverflow.com/questions/19412/how-to-request-a-random-row-in-sql – zod

+0

^這是一個不同的問題 – user2217162

+0

定義「隨機」 – Woot4Moo

回答

0
select distinct c1.ID, c2.category 
from mytable c1 
join mytable c2 ON c1.category = c2.category and c1.ID <> c2.ID 
group by c1.category, c2.ID; 
+0

This works,but let say I want 5 row from each category,would I have to join 5 tables? – user2217162

+0

對於返回行中的每次增加,您需要額外的自加入和按ID分組。例如,要獲得每個類別的3個: 從國家/地區c1選擇不同的c1.ID,c2.category 加入國家/地區c2 ON c1.category = c2.category和c1.ID <> c2.ID 加入國家/地區c3 ON c2.category = c3.category和c1.ID <> c3.ID group by c1.category,c2.ID,c3.ID; – udog

+0

嗨有user2217162,這些答案可以接受嗎? – udog

0

這是一種方式來獲得從每個類別中的兩個隨機行:

select t.* 
from t join 
    (select t.category, substring_index(group_concat(id order by rand()), ',', 2) as ids 
     from t 
     group by category 
    ) tc 
    on find_in_set(t.id, tc.ids) > 0; 

它使用group_concat()將ID以隨機順序放入列表中,選擇前兩個,並返回並找到具有這些ID的行。它很容易推廣到2個以上的ID。