2015-09-28 80 views
0

我有CategoryQuestion與一對多關係表,我想 有3個隨機類別,每個類別有3個隨機問題。如何在一個查詢中做到這一點?MySQL限制加入表

Category 
id 
title 

Question 
id 
title 
cat_id 

輸出示例:

cat_id title ques_id title cat_id 
4  Math 1  1+1? 1 
4  Math 3  2*5? 1 
4  Math 5  3*5? 1 
12  Hist 1  Who. 12 
12  Hist 2  blah 12 
12  Hist 5  blah 12 
15  Phys 1  m=. 15 
15  Phys 3  blah 15 
15  Phys 4  blah 15 
+1

也提供樣本數據以及輸入/輸出 –

+0

我提供了樣本輸出,輸入會很大。假設thera是10-20個類別和100-1000個問題,每個 –

+0

使用程序。 – DevLakshman

回答

0

如果你能回答爲3行,而不是9住,最簡單的方法是:

select c.*, 
     substring_index(group_concat(q.id order by rand()), ',', 3) as question_ids 
from category c join 
    question q 
    on c.id = q.cat_id 
group by c.id 
order by rand(); 

否則,你可以用做變量:

select cq.* 
from (select c.*, q.*, 
      (@rn := if(@c = c.id, @rn + 1, 
         if(@c := c.id, 1, 1) 
         ) 
      ) as rn 
     from (select c.* 
      from category c 
      order by rand() 
      limit 3 
      ) c join 
      question q 
      on c.id = q.cat_id cross join 
      (select @c := 0, @rn := 0) params 
     order by c.id, rand() 
    ) cq 
where rn <= 3; 

當然,您應該選擇實際需要的列而不是使用*