2015-09-28 55 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; 

当然,您应该选择实际需要的列而不是使用*