2013-01-15 110 views
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)SQL左外連接選擇不匹配的記錄?

$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>"; } 
+0

在您的SQL查詢中將33更改爲44 – twoleggedhorse

+0

使用mysqli而不是mysql代替新代碼。 –

+0

不,我想從問題故事中找回未回答的問題,然後將問題ID添加到用戶標識爲這樣: user_id 33 44 33 44 33 33 question_id 2 4 1 3 3 4 –

回答

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

+0

好吧,但我不能爲特定用戶做 –

+0

這非常感謝很多@Radical這是工作100% –

2

我相信你在找什麼的話來說就是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"); 
+0

我同意上面的答案。看到這個在行動:http://www.sqlfiddle.com/#!2/95a0c/2 –

+0

我添加了一個主鍵到user_answer表,因爲你的關鍵是一個複合關鍵。 –

+0

+1。是的,反連接模式是一種可行的方法,其索引定義爲'ON user_answer(user_id,question_id)'。 – spencer7593

0

可能是什麼的答案是把你使用 然後從mysql_fetch_array相同mysql_query檢索「question_id的價值觀和最後,如果你有問題的計數(如果不是你可以使用mysql計數),使用php函數array_diff()來檢索(從增量排序的questi整數值數組on_id或來自'question'表的question_id值數組)

+0

或者,查詢可以被修改,以有效地返回指定的結果集,無論哪一個。 – spencer7593