2016-06-07 53 views
0

我有两个表名为类别和问题。我需要帮助写一个查询来获得随机问题。如果有10个问题,第一个问题将来自第一个类别,第二个问题将从第二个类别继续,并且继续如此,直到显示10个问题。我的表结构看起来像这样MySQL查询获取随机问题

类别 ID |名称

1 | php

2 | jQuery

3 | MySQL

问题 ID |问题| ans1 | ans2 | catid |正确

1 | q1 | a1 | a2 | 1 | a1

2 | q2 | a1 | a2 | 3 | A1

查询我已经是这个

select * from questions where category_id=$category_id ORDER BY RAND() LIMIT 12 
+0

这基本上只是“前N组”的问题的一个变种... –

回答

0

使用我公式解决的问题。这可能很难,但我解决了它。 你可以试试....

//代码在这里开始

//Get maximum value of category id 
    $cid = "select * from category";//Getting category id 
    $cid = mysqli_query($con,$cid);//Run the query 
    $v = array();//Create an array 
    while($d = mysqli_fetch_array($max)){ 
     array_push($v,$d['id']);//Push all id to the array. 
    } 
    //Get single key form the array randomly with php array function array_rand(). 
    $rand = array_rand($v,1); 
    $rand = $v[$rand];//Ultimately get the random category id. 

    //Now use the category id in where clause. 
    $sql = "select * from questions where category_id=$rand LIMIT 12"; 
    $sql = mysqli_query($con,$sql); 
    while($d = mysqli_fetch_array($sql)){//$d = data 
     echo $d['id'].'. '.$d['question'].'<br>';//Display the questions randomly with multiple questions if exists. 
    } 

//代码结束 感谢。

+0

我认为第一个变量不是$ cid,它是$ max – dwerty