1

我已经知道如何进行随机 mysql/php 查询,但是如何跟踪已经查询过的内容不会再次被拉出。用例:一个有 10 个问题的测验。这些问题需要按随机顺序排列。如何跟踪问题(行)2、5、6、8、9 已经回答,但问题 1、3、4、7、10 仍然存在。这是我到目前为止所拥有的:

$current_test = $_SESSION['testid'];
// v v v query for this TEST
$tests = mysql_query("SELECT * FROM the_tests WHERE the_tests.testid=$current_test");
$test = mysql_fetch_array($tests);
// ^ ^ ^ query for this TEST


// v v v query for the QUESTIONS from this Test
// Generate
if ($test['randomize']==1){
    $offset_result = mysql_query("SELECT FLOOR(RAND() * COUNT(*)) AS offset FROM the_questions WHERE the_questions.test_id_q=$current_test");//SELECT FLOOR(RAND() * COUNT(*)) AS offset FROM the_questions WHERE `qid` NOT IN (1,5,6) AND the_questions.test_id_q=1
    $offset_row = mysql_fetch_object($offset_result);
    $offset = $offset_row->offset;
    $questions = mysql_query("SELECT * FROM the_questions WHERE the_questions.test_id_q=$current_test LIMIT $offset, 1 " );
}else{
    $questions = mysql_query("SELECT * FROM the_questions WHERE the_questions.test_id_q=$current_test");
}
$totalQuestions = mysql_query("SELECT * FROM the_questions WHERE the_questions.test_id_q=$current_test");
$totalQs = mysql_num_rows($totalQuestions);
$testQ = mysql_fetch_array($questions);

提前致谢!

4

2 回答 2

1

您正在寻找补充该 SQL WHERE 子句NOT IN (5,23,45);

所以基本上保留一个包含每个随机项目 ID 值的数组并将其提供给您的 SQL 子句。

mysql_query("SELECT FLOOR(RAND() * COUNT(*)) AS offset FROM the_questions WHERE the_questions.test_id_q=$current_test AND the_questions.id NOT IN (".implode(',',$excluded).")");

现在,这提出了另一个问题:$excluded 数组。它应该是暂时的排除还是应该是永久的?如果它不应该是永久性的,则将其存储在会话中(例如: $_SESSION['excluded'] )如果用户在 3 天后来,他可能能够重新回答该问题。

如果这必须是永久性的,那么将已回答该问题的事实存储在专用于该问题的列中,或者,只需检查是否有答案?

mysql_query("SELECT FLOOR(RAND() * COUNT(*)) AS offset FROM the_questions WHERE the_questions.test_id_q=$current_test AND the_questions.answer ==''");
于 2012-05-24T20:33:17.667 回答
1

这是我想出的:

假设 $_SESSION['qList'] 是一个如下所示的数组:

$_SESSION['qList'] = array(1,2,3,4,5,6,7,8,9,10);

当用户提交问题时,会有一个 <input type="hidden" value="5"...> ,其中的值是当前问题的 ID。$eliminateQ下面是这个问题的 ID:

$_SESSION['qList'] = array_diff($_SESSION['qList'],array($eliminateQ));
$_SESSION['qList'] = array_values($_SESSION['qList']);
$questions = mysql_query("SELECT * FROM tan_questions WHERE test_id_q=$current_test AND qid IN (".implode(',',$_SESSION[qList]).") ORDER BY RAND() LIMIT 1");

这导致更新的 qList 数组没有 ID 号 5:

$_SESSION['qList'] = array(1,2,3,4,6,7,8,9,10);

整个事情一直持续到没有问题为止。该实例中有一个 if() 语句将用户转发到结果页面。中提琴!

谢谢@pixeline,您的洞察力。我拿走了您的NOT IN并将其反转为IN。:)

于 2012-05-27T01:51:13.757 回答