Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL限制联接表_Mysql_Sql - Fatal编程技术网

MySQL限制联接表

MySQL限制联接表,mysql,sql,Mysql,Sql,我有一对多关系表的类别和问题,我想 有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

我有一对多关系表的类别和问题,我想 有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

如果您可以接受答案为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;

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

同时提供示例数据,如果使用输入/输出,则输入会很大。假设thera在每个Hwant随机记录中有10-20个类别和100-1000个问题?是的,每个Hwant随机记录中有3个随机类别和3个随机问题在子查询中是否支持限制?