使用php和mysql从另一个表中使用多个ID从表中获取数据

时间:2016-06-23 07:04:19

标签: php mysql

我有评估ID的评估。评估从多个问题库类别中读取问题(每个类别随机抽取的具体问题数量)

我需要进行查询以使用php和mysql从不同的类别中收集问题。我试过了:

$query = "SELECT * FROM `questions`  WHERE `category_id` IN (SELECT   `category_id` FROM `assessment_category` WHERE `assessment_id`= $id   ORDER BY RAND() LIMIT 0,$number)";

但是它给出了我的错误服务器版本不支持限制。

我也使用了内连接

$query ="SELECT *   FROM questions AS v INNER JOIN (SELECT category_id FROM assessment_category WHERE assessment_id = $id ) as v2  ON v.category_id = v2.category_id  ORDER BY RAND() LIMIT 0,$number";

但也行不通。任何帮助将不胜感激。

感谢。

1 个答案:

答案 0 :(得分:0)

这对我有用:

$cats // data for categories
$query2 = "";
$numItems = count($cats);
$i = 0;
foreach($cats as $cat){
    $cat_id = $cat['category_id'];
    $number = $cat['number_of_questions'];
      if(++$i === $numItems) {
            $query2 .= " (SELECT * FROM `questions` WHERE category_id = $cat_id ORDER BY RAND() LIMIT $number)";
      }else{
            $query2 .= "(SELECT * FROM `questions` WHERE category_id = $cat_id ORDER BY RAND() LIMIT $number)
                UNION ALL ";
      }                          
    $questions // execute your query;
}

全部谢谢