我有Category
和Question
一对多关系表,我想
有3个随机类别,每个类别有3个随机问题。如何在一个查询中执行此操作?
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
答案 0 :(得分: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;
当然,您应该选择实际需要的列,而不是使用*
。