1
question table
========================
question_id
1
2
3
4


user_answer table
========================
user_id  question_id
33       2
44       4
33       1
44       3

此代码将返回问题 ID(2 和 1)我想要的是从表问题中检索另一个问题 ID,所以我希望结果为(3 和 4)

   $fadi = mysql_query("SELECT * FROM question
         LEFT OUTER JOIN user_answer
           ON user_answer.question_id = question.question_id
              WHERE user_answer.user_id = 33");

   Print "<table border cellpadding=3>";
   while($info = mysql_fetch_array($fadi))
   { Print "<tr>"; 
    Print "<th>question </th> <td>".$info['question_id'] . "</td></tr>";
   }  Print "</table>"; }
4

3 回答 3

2

我相信您正在寻找的是 IS NULL 字样:

$fadi = mysql_query("SELECT * FROM question
     LEFT OUTER JOIN user_answer
       ON user_answer.question_id = question.question_id
          AND user_answer.user_id = 33
       WHERE user_answer.question_id IS NULL");

您可以更进一步,仅从问题表中检索问题 ID:

$fadi = mysql_query("SELECT question.question_id FROM question
     LEFT OUTER JOIN user_answer
       ON user_answer.question_id = question.question_id
          AND user_answer.user_id = 33
       WHERE user_answer.question_id IS NULL"); 
于 2013-01-15T23:23:10.220 回答
1

编辑:改进版。

  $fadi = mysql_query("SELECT * FROM question WHERE  question.question_id NOT IN (SELECT user_answer.question_id FROM user_answer WHERE user_answer.user_id = 33)");

   Print "<table border cellpadding=3>";
   while($info = mysql_fetch_array($fadi))
   { Print "<tr>"; 
    Print "<th>question </th> <td>".$info['question_id'] . "</td></tr>";
   }  Print "</table>"; }

MySQLi 版本:

  $link = mysqli_connect($hostname, $username, $password, $database);
  if (!$link){ 
  echo('Unable to connect to database');
  }
  else{
  $fadi = mysqli_query("SELECT * FROM question WHERE  question.question_id NOT IN (SELECT user_answer.question_id FROM user_answer WHERE user_answer.user_id = 33)", $link);

   Print "<table border cellpadding=3>";
   while($info = mysqli_fetch_array($fadi,MYSQL_BOTH))
   { Print "<tr>"; 
    Print "<th>question </th> <td>".$info['question_id'] . "</td></tr>";
   }  Print "</table>"; }

  }
  mysqli_close($link);

实际操作:http ://www.sqlfiddle.com/#!2/27b6f/21

于 2013-01-15T23:31:14.317 回答
0

可能的答案是mysql_querymysql_fetch_array检索“question_id”值中获取您使用的相同值,最后,如果您有问题的计数(如果没有,您可以使用 mysql 计数),使用 php 函数array_diff()检索(从增量排序的 question_id 整数值数组或来自“问题”表的 question_id 值数组)正是您想要的

于 2013-01-15T23:46:55.407 回答